Cataclysm DDA
Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes | Protected Member Functions | Private Member Functions | Private Attributes | List of all members
npc Class Reference

#include <npc.h>

Inheritance diagram for npc:
Character Creature visitable viewer read_only_visitable standard_npc

Public Member Functions

 npc ()
 
 npc (const npc &)=delete
 
 npc (npc &&) noexcept(map_is_noexcept)
 
npcoperator= (const npc &)=delete
 
npcoperator= (npc &&) noexcept(list_is_noexcept)
 
 ~npc () override
 
bool is_avatar () const override
 
bool is_npc () const override
 
npcas_npc () override
 
const npcas_npc () const override
 
void load_npc_template (const string_id< npc_template > &ident)
 
void npc_dismount ()
 
void randomize (const npc_class_id &type=npc_class_id::NULL_ID(), const npc_template_id &tem_id=npc_template_id::NULL_ID())
 
void randomize_from_faction (faction *fac)
 
void apply_ownership_to_inv ()
 
void clear_personality_traits ()
 
void generate_personality_traits ()
 
void learn_ma_styles_from_traits ()
 
int get_faction_ver () const
 
void set_faction_ver (int new_version)
 
bool has_faction_relationship (const Character &you, npc_factions::relationship flag) const
 
void set_fac (const faction_id &id)
 
factionget_faction () const override
 
faction_id get_fac_id () const
 
void spawn_at_omt (const tripoint_abs_omt &p)
 Spawns the NPC on a random square within the given OMT. More...
 
void spawn_at_precise (const tripoint_abs_ms &p)
 Spawns the NPC on the specified map square. More...
 
void place_on_map ()
 Places the NPC on the map. More...
 
void add_new_mission (mission *miss)
 See dialogue_chatbin::add_new_mission. More...
 
void update_missions_target (character_id old_character, character_id new_character)
 
std::pair< skill_id, int > best_combat_skill (combat_skills subset) const
 
void starting_weapon (const npc_class_id &type)
 
void deserialize (const JsonObject &data) override
 
void serialize (JsonOut &json) const override
 
void export_to (const cata_path &path) const
 
void import_and_clean (const cata_path &path)
 Read json and apply post-import cleanup. More...
 
nc_color basic_symbol_color () const override
 Creature symbol color. More...
 
int print_info (const catacurses::window &w, int line, int vLines, int column) const override
 Write information about this creature. More...
 
std::string opinion_text () const
 
int faction_display (const catacurses::window &fac_w, int width) const
 
std::string describe_mission () const
 
std::string name_and_activity () const
 
std::string name_and_maybe_activity () const override
 
std::string get_current_status () const
 Returns current status (Sleeping, Guarding, In Combat, etc.), or current activity. More...
 
std::string get_current_activity () const
 Returns the current activity name (reading, disassembling, etc.), or "nothing". More...
 
void form_opinion (const Character &you)
 
npc_opinion get_opinion_values (const Character &you) const
 
std::string pick_talk_topic (const Character &u)
 
std::string const & get_specified_talk_topic (std::string const &topic_id)
 
float character_danger (const Character &u) const
 
float vehicle_danger (int radius) const
 
void pretend_fire (npc *source, int shots, item &gun)
 
bool turned_hostile () const
 
int hostile_anger_level () const
 
void make_angry ()
 
void on_attacked (const Creature &attacker)
 
int assigned_missions_value ()
 
bool is_enemy () const
 
bool is_following () const
 
bool is_obeying (const Character &p) const override
 
bool is_hallucination () const override
 
bool is_electrical () const override
 
bool is_friendly (const Character &p) const
 
bool is_leader () const
 
bool is_walking_with () const
 
bool is_ally (const Character &p) const override
 
bool is_player_ally () const
 
bool is_stationary (bool include_guards=true) const
 
bool is_guarding () const
 
bool is_patrolling () const
 
bool within_boundaries_of_camp () const
 
bool has_player_activity () const
 is performing a player_activity More...
 
bool is_travelling () const
 
bool is_minion () const
 Trusts you a lot. More...
 
bool guaranteed_hostile () const
 Is enemy or will turn into one (can't be convinced not to attack). More...
 
Attitude attitude_to (const Creature &other) const override
 Attitude (of this creature) towards another creature. More...
 
void mutiny ()
 
mfaction_id get_monster_faction () const override
 For mutant NPCs. More...
 
int follow_distance () const
 
void shop_restock ()
 
std::string get_restock_interval () const
 
bool is_shopkeeper () const
 
int minimum_item_value () const
 
void update_worst_item_value ()
 
double value (const item &it) const
 
double value (const item &it, double market_price) const
 
faction_price_rule const * get_price_rules (item const &it) const
 
bool wear_if_wanted (const item &it, std::string &reason)
 
bool can_read (const item &book, std::vector< std::string > &fail_reasons)
 
time_duration time_to_read (const item &book, const Character &reader) const
 
void do_npc_read (bool ebook=false)
 
void stow_item (item &it)
 
bool wield (item &it) override
 Removes currently wielded item (if any) and replaces it with the target item. More...
 
void drop (const drop_locations &what, const tripoint &target, bool stash) override
 
bool adjust_worn ()
 
bool has_healing_item (healing_options try_to_fix)
 
healing_options patient_assessment (const Character &c)
 
healing_options has_healing_options ()
 
healing_options has_healing_options (healing_options try_to_fix)
 
itemget_healing_item (healing_options try_to_fix, bool first_best=false)
 
bool has_painkiller ()
 
bool took_painkiller () const
 
void use_painkiller ()
 
void activate_item (item &it)
 
bool has_identified (const itype_id &) const override
 Note that we've read a book at least once. More...
 
void identify (const item &) override
 
bool will_accept_from_player (const item &it) const
 Is the item safe or does the NPC trust you enough? Is not recursive, only checks the item that is the parameter. More...
 
bool wants_to_sell (const item_location &it) const
 
ret_val< void > wants_to_sell (const item_location &it, int at_price) const
 
bool wants_to_buy (const item &it) const
 
ret_val< void > wants_to_buy (const item &, int at_price) const
 
bool will_exchange_items_freely () const
 
int max_credit_extended () const
 
int max_willing_to_owe () const
 
void regen_ai_cache ()
 
const Creaturecurrent_target () const
 
Creaturecurrent_target ()
 
const Creaturecurrent_ally () const
 
Creaturecurrent_ally ()
 
tripoint good_escape_direction (bool include_pos=true)
 
float danger_assessment () const
 
float average_damage_dealt ()
 
bool bravery_check (int diff) const
 
bool emergency () const
 
bool emergency (float danger) const
 
bool is_active () const
 
template<typename ... Args>
void say (const char *const line, Args &&... args) const
 
void say (const std::string &line, sounds::sound_t spriority=sounds::sound_t::speech) const
 
int indoor_voice () const
 
void decide_needs ()
 
void reboot ()
 
void die (Creature *killer) override
 Empty function. More...
 
bool is_dead () const
 
void prevent_death () override
 
int smash_ability () const override
 
void activate_combat_cbms ()
 
void deactivate_combat_cbms ()
 
bool recharge_cbm ()
 
bool wants_to_recharge_cbm ()
 
bool can_use_offensive_cbm () const
 
bool use_bionic_by_id (const bionic_id &cbm_id, bool eff_only=false)
 
bool activate_bionic_by_id (const bionic_id &cbm_id, bool eff_only=false)
 
bool deactivate_bionic_by_id (const bionic_id &cbm_id, bool eff_only=false)
 
void discharge_cbm_weapon (bool fired=true, bool stow_real_weapon=false)
 
void deactivate_or_discharge_bionic_weapon (bool stow_real_weapon=false)
 
void check_or_use_weapon_cbm (const bionic_id &cbm_id)
 
void activate_combat_items ()
 
void deactivate_combat_items ()
 
void prepare_for_combat ()
 
void cleanup_on_no_danger ()
 
bool complain_about (const std::string &issue, const time_duration &dur, const std::string &speech, bool force=false, sounds::sound_t priority=sounds::sound_t::speech)
 
void warn_about (const std::string &type, const time_duration &d=10_minutes, const std::string &name="", int range=-1, const tripoint &danger_pos=tripoint_zero)
 
std::string distance_string (int range) const
 
bool complain ()
 
void handle_sound (sounds::sound_t priority, const std::string &description, int heard_volume, const tripoint &spos)
 
void witness_thievery (item *it) override
 
void shift (const point &s)
 
void move ()
 
void execute_action (npc_action action)
 
void process_turn () override
 Handles end-of-turn processing. More...
 
bool invoke_item (item *, const tripoint &pt, int pre_obtain_moves) override
 Asks how to use the item (if it has more than one use_method) and uses it. More...
 
bool invoke_item (item *used, const std::string &method) override
 
bool invoke_item (item *) override
 As above two, but with position equal to current position. More...
 
float evaluate_monster (const monster &target, int dist) const
 rates how dangerous a target is More...
 
float evaluate_character (const Character &candidate, bool my_gun, bool enemy)
 
float evaluate_self (bool my_gun)
 
void assess_danger ()
 
void act_on_danger_assessment ()
 
bool is_safe () const
 
npc_action method_of_fleeing ()
 
npc_action method_of_attack ()
 
void evaluate_best_attack (const Creature *target)
 
float estimate_armour (const Character &candidate) const
 
npc_action address_needs ()
 
npc_action address_needs (float danger)
 
npc_action address_player ()
 
npc_action long_term_goal_action ()
 
int evaluate_sleep_spot (tripoint_bub_ms p)
 
bool scan_new_items ()
 
double evaluate_weapon (item &maybe_weapon, bool can_use_gun, bool use_silent) const
 
itemevaluate_best_weapon () const
 
bool wield_better_weapon ()
 
double confidence_mult () const
 
int confident_shoot_range (const item &it, int at_recoil) const
 
int confident_gun_mode_range (const gun_mode &gun, int at_recoil) const
 
int confident_throw_range (const item &, Creature *) const
 
void invalidate_range_cache ()
 
bool wont_hit_friend (const tripoint &tar, const item &it, bool throwing) const
 
bool enough_time_to_reload (const item &gun) const
 
bool can_reload_current ()
 Can reload currently wielded gun? More...
 
item_location find_reloadable ()
 Has a gun or magazine that can be reloaded. More...
 
item_location find_usable_ammo (const item_location &weap)
 Finds ammo the NPC could use to reload a given object. More...
 
item_location find_usable_ammo (const item_location &weap) const
 
item::reload_option select_ammo (const item_location &base, bool prompt=false, bool empty=true) override
 Select suitable ammo with which to reload the item. More...
 
bool dispose_item (item_location &&obj, const std::string &prompt=std::string()) override
 Drop, wear, stash or otherwise try to dispose of an item consuming appropriate moves. More...
 
void update_cardio_acc () override
 
void aim (const Target_attributes &target_attributes)
 
void do_reload (const item_location &it)
 
bool update_path (const tripoint &p, bool no_bashing=false, bool force=true)
 Tries to find path to p. More...
 
bool update_path (const tripoint_bub_ms &p, bool no_bashing=false, bool force=true)
 
void set_guard_pos (const tripoint_abs_ms &p)
 
bool can_open_door (const tripoint &p, bool inside) const
 
bool can_move_to (const tripoint &p, bool no_bashing=false) const
 
void move_to (const tripoint &p, bool no_bashing=false, std::set< tripoint > *nomove=nullptr)
 
void move_to_next ()
 
void avoid_friendly_fire ()
 
void escape_explosion ()
 
void move_away_from (const tripoint &p, bool no_bash_atk=false, std::set< tripoint > *nomove=nullptr)
 
void move_away_from (const std::vector< sphere > &spheres, bool no_bashing=false)
 
void worker_downtime ()
 
bool find_job_to_perform ()
 
void move_pause ()
 
void set_movement_mode (const move_mode_id &mode) override
 
const pathfinding_settingsget_pathfinding_settings () const override
 Returns settings for pathfinding. More...
 
const pathfinding_settingsget_pathfinding_settings (bool no_bashing) const
 
std::unordered_set< tripointget_path_avoid () const override
 Returns a set of points we do not want to path through. More...
 
void see_item_say_smth (const itype_id &object, const std::string &smth)
 
bool can_take_that (const item &it)
 
bool wants_take_that (const item &it)
 
bool would_take_that (const item &it, const tripoint &p)
 
void find_item ()
 
void pick_up_item ()
 
std::list< itempick_up_item_map (const tripoint &where)
 Picks up items and returns a list of them. More...
 
std::list< itempick_up_item_vehicle (vehicle &veh, int part_index)
 
bool has_item_whitelist () const
 
bool item_name_whitelisted (const std::string &to_match)
 
bool item_whitelisted (const item &it)
 
bool find_corpse_to_pulp ()
 Returns true if it finds one. More...
 
bool can_do_pulp ()
 Returns true if NPC can do pulp in this turn. More...
 
bool do_player_activity ()
 perform a player activity, returning true if it took up the turn More...
 
bool alt_attack ()
 
void heal_player (Character &patient)
 
void heal_self ()
 
void pretend_heal (Character &patient, item used)
 
void mug_player (Character &mark)
 
void look_for_player (const Character &sought)
 
bool saw_player_recently () const
 
bool consume_food ()
 Returns true if food was consumed, false otherwise. More...
 
bool consume_food_from_camp ()
 
int get_thirst () const override
 
bool has_omt_destination () const
 
void set_omt_destination ()
 
void go_to_omt_destination ()
 
void reach_omt_destination ()
 
void guard_current_pos ()
 
void add_msg_if_npc (const std::string &msg) const override
 
void add_msg_if_npc (const game_message_params &params, const std::string &msg) const override
 
void add_msg_player_or_npc (const std::string &player_msg, const std::string &npc_msg) const override
 
void add_msg_player_or_npc (const game_message_params &params, const std::string &player_msg, const std::string &npc_msg) const override
 
void add_msg_if_player (const std::string &) const override
 
void add_msg_if_player (const game_message_params &, const std::string &) const override
 
void add_msg_player_or_say (const std::string &player_msg, const std::string &npc_speech) const override
 
void add_msg_player_or_say (const game_message_params &params, const std::string &player_msg, const std::string &npc_speech) const override
 
bool query_yn (const std::string &mes) const override
 
std::string extended_description () const override
 
std::string get_epilogue () const
 
std::pair< std::string, nc_colorhp_description () const
 
float speed_rating () const override
 Returns an approximate number of tiles this creature can travel per turn. More...
 
void travel_overmap (const tripoint_abs_omt &pos)
 Note: this places NPC on a given position in CURRENT MAP coordinates. More...
 
npc_attitude get_attitude () const override
 
void set_attitude (npc_attitude new_attitude)
 
void set_mission (npc_mission new_mission)
 
bool has_activity () const
 
bool has_job () const
 
npc_attitude get_previous_attitude ()
 
npc_mission get_previous_mission () const
 
void revert_after_activity ()
 
void do_npc_craft (const std::optional< tripoint > &loc=std::nullopt, const recipe_id &goto_recipe=recipe_id())
 
item_location get_item_to_craft ()
 
const std::vector< weak_ptr_fast< Creature > > & get_cached_friends () const
 
std::optional< int > closest_enemy_to_friendly_distance () const
 
const dialogue_chatbin_snippetschat_snippets () const
 
const std::shared_ptr< npc_attack > & get_current_attack () const
 
const npc_attack_ratingget_current_attack_evaluation () const
 
void on_unload ()
 Do some cleanup and caching as npc is being unloaded from map. More...
 
void on_load ()
 Retroactively update npc. More...
 
void npc_update_body ()
 Update body, but throttled. More...
 
bool get_known_to_u () const
 
void set_known_to_u (bool known)
 
void set_companion_mission (npc &p, const mission_id &miss_id)
 Set up (start) a companion mission. More...
 
void set_companion_mission (const tripoint_abs_omt &omt_pos, const std::string &role_id, const mission_id &miss_id)
 
void set_companion_mission (const tripoint_abs_omt &omt_pos, const std::string &role_id, const mission_id &miss_id, const tripoint_abs_omt &destination)
 
void reset_companion_mission ()
 Unset a companion mission. Precondition: !has_companion_mission() More...
 
std::optional< tripoint_abs_omtget_mission_destination () const
 
bool has_companion_mission () const
 
npc_companion_mission get_companion_mission () const
 
attitude_group get_attitude_group (npc_attitude att) const
 
void set_unique_id (const std::string &id)
 
std::string get_unique_id () const
 
virtual bool invoke_item (item *, const tripoint &pt, int pre_obtain_moves=-1)
 Asks how to use the item (if it has more than one use_method) and uses it. More...
 
virtual bool invoke_item (item *, const std::string &, const tripoint &pt, int pre_obtain_moves=-1)
 As above, but with a pre-selected method. More...
 
virtual bool invoke_item (item *)
 As above two, but with position equal to current position. More...
 
virtual bool invoke_item (item *, const std::string &)
 
void add_msg_player_or_npc (const std::string &player_msg, const std::string &npc_str) const override
 
void add_msg_player_or_npc (const game_message_params &params, const std::string &player_msg, const std::string &npc_msg) const override
 
virtual void add_msg_player_or_npc (const std::string &, const std::string &) const
 
virtual void add_msg_player_or_npc (const game_message_params &, const std::string &, const std::string &) const
 
void add_msg_player_or_npc (const translation &, const translation &) const
 
void add_msg_player_or_npc (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_npc (const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
void add_msg_if_player (const std::string &msg) const override
 
void add_msg_if_player (const game_message_params &params, const std::string &msg) const override
 
virtual void add_msg_if_player (const std::string &) const
 
virtual void add_msg_if_player (const game_message_params &, const std::string &) const
 
void add_msg_if_player (const translation &) const
 
void add_msg_if_player (const game_message_params &, const translation &) const
 
template<typename ... Args>
void add_msg_if_player (const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const translation &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const translation &msg, Args &&... args) const
 
void add_msg_player_or_say (const std::string &player_msg, const std::string &npc_speech) const override
 
void add_msg_player_or_say (const game_message_params &params, const std::string &player_msg, const std::string &npc_speech) const override
 
virtual void add_msg_player_or_say (const std::string &, const std::string &) const
 
virtual void add_msg_player_or_say (const game_message_params &, const std::string &, const std::string &) const
 
void add_msg_player_or_say (const translation &, const translation &) const
 
void add_msg_player_or_say (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_say (const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
- Public Member Functions inherited from Character
 Character (const Character &)=delete
 
Characteroperator= (const Character &)=delete
 
 ~Character () override
 
void initialize (bool learn_recipes=true)
 
Characteras_character () override
 
const Characteras_character () const override
 
character_id getID () const
 
void setID (character_id i, bool force=false)
 sets the ID, will only succeed when the current id is not valid allows forcing a -1 id which is required for templates to not throw errors More...
 
field_type_id bloodType () const override
 
field_type_id gibType () const override
 
bool is_warm () const override
 
bool in_species (const species_id &spec) const override
 
int get_str () const
 Getters for stats exclusive to characters. More...
 
int get_dex () const
 
int get_per () const
 
int get_int () const
 
int get_str_base () const
 
int get_dex_base () const
 
int get_per_base () const
 
int get_int_base () const
 
int get_str_bonus () const
 
int get_dex_bonus () const
 
int get_per_bonus () const
 
int get_int_bonus () const
 
int get_arms_power_use () const
 Getters for above stats. More...
 
int get_legs_power_use () const
 
float get_arms_stam_mult () const
 
float get_legs_stam_mult () const
 
std::vector< speed_bonus_effectget_speed_bonus_effects () const
 
int get_speed () const override
 
int get_enchantment_speed_bonus () const
 
int get_arm_str () const
 
int get_eff_per () const override
 
int ranged_dex_mod () const
 
int ranged_per_mod () const
 
void set_str_bonus (int nstr)
 Setters for stats exclusive to characters. More...
 
void set_dex_bonus (int ndex)
 
void set_per_bonus (int nper)
 
void set_int_bonus (int nint)
 
void mod_str_bonus (int nstr)
 
void mod_dex_bonus (int ndex)
 
void mod_per_bonus (int nper)
 
void mod_int_bonus (int nint)
 
void mod_speed_bonus (int nspeed, const std::string &desc)
 
int get_lifestyle () const
 Getters for health values exclusive to characters. More...
 
int get_daily_health () const
 
int get_health_tally () const
 
void mod_livestyle (int nhealthy)
 Modifiers for health values exclusive to characters. More...
 
void mod_daily_health (int nhealthy_mod, int cap)
 
void mod_health_tally (int mod)
 
void set_lifestyle (int nhealthy)
 Setters for health values exclusive to characters. More...
 
void set_daily_health (int nhealthy_mod)
 
int get_stored_kcal () const
 Getter for need values exclusive to characters. More...
 
int get_healthy_kcal () const
 
float get_kcal_percent () const
 
int kcal_speed_penalty () const
 
int get_hunger () const
 
int get_starvation () const
 
virtual int get_instant_thirst () const
 
time_duration get_daily_sleep () const
 
void mod_daily_sleep (time_duration mod)
 
void reset_daily_sleep ()
 
time_duration get_continuous_sleep () const
 
void mod_continuous_sleep (time_duration mod)
 
void reset_continuous_sleep ()
 
int get_sleepiness () const
 
int get_sleep_deprivation () const
 
void mod_stored_kcal (int nkcal, bool ignore_weariness=false)
 Modifiers for need values exclusive to characters. More...
 
void mod_hunger (int nhunger)
 
void mod_thirst (int nthirst)
 
void mod_sleepiness (int nsleepiness)
 
void mod_sleep_deprivation (int nsleep_deprivation)
 
void set_stored_kcal (int kcal)
 Setters for need values exclusive to characters. More...
 
void set_hunger (int nhunger)
 
void set_thirst (int nthirst)
 
void set_sleepiness (int nsleepiness)
 
void set_sleepiness (sleepiness_levels nsleepiness)
 
void set_sleep_deprivation (int nsleep_deprivation)
 
void gravity_check ()
 
void stagger ()
 
void mod_stat (const std::string &stat, float modifier) override
 
int get_standard_stamina_cost (const item *thrown_item=nullptr) const
 
int get_fat_to_hp () const
 Get bonus to max_hp from excess stored fat. More...
 
creature_size get_size () const override
 Get size class of character. More...
 
void recalculate_size ()
 Recalculate size class of character. More...
 
std::string disp_name (bool possessive=false, bool capitalize_first=false) const override
 Returns either "you" or the player's name. More...
 
std::string skin_name () const override
 Returns the name of the player's outer layer, e.g. More...
 
void set_fac_id (const std::string &my_fac_id)
 
const professionget_profession () const
 
std::set< const profession * > get_hobbies () const
 
bool has_mission_item (int mission_id) const
 
int effective_dispersion (int dispersion, bool zoom=false) const
 
int get_character_parallax (bool zoom=false) const
 
std::vector< aim_typeget_aim_types (const item &gun) const
 
int point_shooting_limit (const item &gun) const
 
double fastest_aiming_method_speed (const item &gun, double recoil, const Target_attributes &target_attributes=Target_attributes(), std::optional< std::reference_wrapper< const parallax_cache >> parallax_cache=std::nullopt) const
 
int most_accurate_aiming_method_limit (const item &gun) const
 
double aim_factor_from_volume (const item &gun) const
 
double aim_factor_from_length (const item &gun) const
 
aim_mods_cache gen_aim_mods_cache (const item &gun) const
 
float get_modifier (const character_modifier_id &mod, const skill_id &skill=skill_id::NULL_ID()) const
 
bool has_gun_for_ammo (const ammotype &at) const
 Check whether the player has a gun that uses the given type of ammo. More...
 
bool has_magazine_for_ammo (const ammotype &at) const
 
double aim_per_move (const item &gun, double recoil, const Target_attributes &target_attributes=Target_attributes(), std::optional< std::reference_wrapper< const aim_mods_cache >> aim_cache=std::nullopt) const
 
int get_dodges_left () const
 
void set_dodges_left (int dodges)
 
void mod_dodges_left (int mod)
 
void consume_dodge_attempts ()
 
ret_val< void > can_try_doge (bool ignore_dodges_left=false) const
 
float get_stamina_dodge_modifier () const
 
void on_dodge (Creature *source, float difficulty, float training_level=0.0f) override
 Called after the player has successfully dodged an attack. More...
 
void on_try_dodge () override
 Called after the player has tryed to dodge an attack. More...
 
float get_dodge_base () const override
 Combat getters. More...
 
float dodge_roll () const override
 Returns the player's dodge_roll to be compared against an aggressor's hit_roll() More...
 
float get_dodge () const override
 Returns Creature::get_dodge() modified by any Character effects. More...
 
int get_spell_resist () const override
 in this case spell resistance is just the spellcraft skill for characters. More...
 
bool uncanny_dodge () override
 Handles the uncanny dodge bionic and effects, returns true if the player successfully dodges. More...
 
bool check_avoid_friendly_fire () const override
 
float get_hit_base () const override
 
void tally_organic_size ()
 total hitsize of all non cybernetic body parts More...
 
float get_cached_organic_size () const
 
void recalc_limb_energy_usage ()
 Called on limb change to update the usage values. More...
 
int sight_range (float light_level) const override
 Returns the player's sight range. More...
 
int unimpaired_range () const
 Returns the player maximum vision range factoring in mutations, diseases, and other effects. More...
 
bool overmap_los (const tripoint_abs_omt &omt, int sight_points) const
 Returns true if overmap tile is within player line-of-sight. More...
 
int overmap_sight_range (float light_level) const
 Returns the distance the player can see on the overmap. More...
 
int clairvoyance () const
 Returns the distance the player can see through walls. More...
 
bool sight_impaired () const
 Returns true if the player has some form of impaired sight. More...
 
bool has_alarm_clock () const
 Returns true if the player or their vehicle has an alarm clock. More...
 
bool has_watch () const
 Returns true if the player or their vehicle has a watch. More...
 
void action_taken ()
 Called after every action, invalidates player caches. More...
 
bool is_on_ground () const override
 Returns true if the player is knocked over, has broken legs or is lying down. More...
 
int swim_speed () const
 Returns the player's movecost for swimming across water tiles. More...
 
float get_melee () const override
 Returns melee skill level, to be used to throttle dodge practice. More...
 
void add_miss_reason (const std::string &reason, unsigned int weight)
 Adds a reason for why the player would miss a melee attack. More...
 
void clear_miss_reasons ()
 Clears the list of reasons for why the player would miss a melee attack. More...
 
std::string get_miss_reason ()
 Returns an explanation for why the player would miss a melee attack. More...
 
void regen (int rate_multiplier)
 Handles passive regeneration of pain and maybe hp. More...
 
ret_val< void > can_takeoff (const item &it, const std::list< item > *res=nullptr)
 Check player capable of taking off an item. More...
 
std::pair< int, int > gunmod_installation_odds (const item_location &gun, const item &mod) const
 
void recalc_speed_bonus ()
 Calculates the various speed bonuses we will get from mutations, etc. More...
 
void set_underwater (bool)
 
bool is_fae () const override
 
bool is_nether () const override
 
bool has_mind () const override
 
stat_mod get_pain_penalty () const
 Returns the effect of pain on stats. More...
 
int get_lift_str () const
 returns players strength adjusted by any traits that affect strength during lifting jobs More...
 
bool takeoff (item_location loc, std::list< item > *res=nullptr)
 Takes off an item, returning false on fail. More...
 
bool takeoff (int pos)
 
virtual void update_health ()
 Handles health fluctuations over time. More...
 
void update_body ()
 Updates all "biology" by one turn. More...
 
void update_body (const time_point &from, const time_point &to)
 Updates all "biology" as if time between from and to passed. More...
 
void update_stomach (const time_point &from, const time_point &to)
 Updates the stomach to give accurate hunger messages. More...
 
void update_enchantment_mutations ()
 Updates the mutations from enchantments. More...
 
bool needs_food () const
 Returns true if character needs food, false if character is an NPC with NO_NPC_FOOD set. More...
 
void update_needs (int rate_multiplier)
 Increases hunger, thirst, sleepiness and stimulants wearing off. More...
 
needs_rates calc_needs_rates () const
 
void calc_sleep_recovery_rate (needs_rates &rates) const
 
void check_needs_extremes ()
 Kills the player if too hungry, stimmed up etc., forces tired player to sleep and prints warnings. More...
 
void get_sick (bool is_flu=false)
 Handles the chance to be infected by random diseases. More...
 
bool is_hibernating () const
 Returns if the player has hibernation mutation and is asleep and well fed. More...
 
void update_bodytemp ()
 Maintains body temperature. More...
 
void update_frostbite (const bodypart_id &bp, int FBwindPower, const std::map< bodypart_id, int > &warmth_per_bp)
 
void temp_equalizer (const bodypart_id &bp1, const bodypart_id &bp2)
 Equalizes heat between body parts. More...
 
comfort_response_t base_comfort_value (const tripoint_bub_ms &p) const
 Rate point's ability to serve as a bed. More...
 
int focus_equilibrium_sleepiness_cap (int equilibrium) const
 Returns focus equilibrium cap due to sleepiness. More...
 
int calc_focus_equilibrium (bool ignore_pain=false) const
 Uses morale and other factors to return the character's focus target goto value. More...
 
int calc_focus_change () const
 Calculates actual focus gain/loss value from focus equilibrium. More...
 
void update_mental_focus ()
 Uses calc_focus_change to update the character's current focus. More...
 
void reset_bonuses () override
 Resets the value of all bonus fields to 0. More...
 
void reset_stats () override
 Resets stats, and applies effects in an idempotent manner. More...
 
void reset () override
 Handles stat and bonus reset. More...
 
int encumb (const bodypart_id &bp) const
 Returns ENC provided by armor, etc. More...
 
int avg_encumb_of_limb_type (body_part_type::type part_type) const
 
units::mass get_weight () const override
 Returns body weight plus weight of inventory and worn/wielded items. More...
 
void print_encumbrance (ui_adaptor &ui, const catacurses::window &win, int line=-1, const item *selected_clothing=nullptr) const
 
bool is_wearing_power_armor (bool *hasHelmet=nullptr) const
 Returns true if the character is wearing power armor. More...
 
bool is_wearing_active_power_armor () const
 Returns true if the character is wearing active power. More...
 
bool is_wearing_active_optcloak () const
 Returns true if the player is wearing an active optical cloak. More...
 
std::pair< int, int > climate_control_strength () const
 Returns strength of any climate control affecting character, for heating and chilling respectively. More...
 
std::map< bodypart_id, int > get_wind_resistance (const std::map< bodypart_id, std::vector< const item * >> &clothing_map) const
 Returns wind resistance provided by armor, etc. More...
 
bool is_blind () const
 Returns true if the player isn't able to see. More...
 
bool is_invisible () const
 
int visibility (bool check_color=false, int stillness=0) const
 Checks is_invisible() as well as other factors. More...
 
float active_light () const
 Returns character luminosity based on the brightest active item they are carrying. More...
 
bool sees_with_specials (const Creature &critter) const
 
body_part_set exclusive_flag_coverage (const flag_id &flag) const
 Bitset of all the body parts covered only with items with flag (or nothing) More...
 
bool move_effects (bool attacking) override
 Processes effects which may prevent the Character from moving (bear traps, crushed, etc.). More...
 
void wait_effects (bool attacking=false)
 
bool try_remove_grab (bool attacking=false)
 Series of checks to remove effects for waiting or moving. More...
 
void try_remove_downed ()
 
void try_remove_bear_trap ()
 
void try_remove_lightsnare ()
 
void try_remove_heavysnare ()
 
void try_remove_crushed ()
 
void try_remove_webs ()
 
void try_remove_impeding_effect ()
 
bool can_escape_trap (int difficulty, bool manip) const
 
bool movement_mode_is (const move_mode_id &mode) const
 Check against the character's current movement mode. More...
 
move_mode_id current_movement_mode () const
 
bool is_running () const
 
bool is_walking () const
 
bool is_crouching () const
 
bool is_prone () const
 
int footstep_sound () const
 
int clatter_sound () const
 
void make_footstep_noise () const
 
void make_clatter_sound () const
 
bool can_switch_to (const move_mode_id &mode) const
 
steed_type get_steed_type () const
 
int get_instability_per_category (const mutation_category_id &categ) const
 Generates an integer based on how many times we've gained non-negative mutations. More...
 
void expose_to_disease (const diseasetype_id &dis_type)
 Determine if character is susceptible to dis_type and if so apply the symptoms. More...
 
void recalc_hp ()
 Recalculates HP after a change to max strength or enchantment. More...
 
void update_body_wetness (const w_point &weather)
 Maintains body wetness and handles the rate at which the player dries. More...
 
void recalc_sight_limits ()
 Modifies the player's sight values Must be called when any of the following change: This must be called when any of the following change: More...
 
float get_vision_threshold (float light_level) const
 Returns the apparent light level at which the player can see. More...
 
void flag_encumbrance ()
 Flag encumbrance for updating. More...
 
void check_item_encumbrance_flag ()
 Checks worn items for the "RESET_ENCUMBRANCE" flag, which indicates that encumbrance may have changed and require recalculating. More...
 
bool natural_attack_restricted_on (const bodypart_id &bp) const
 Returns true if the character is wearing something on the entered body_part, ignoring items with the ALLOWS_NATURAL_ATTACKS flag. More...
 
bool natural_attack_restricted_on (const sub_bodypart_id &bp) const
 
bool is_quiet () const
 Returns true if the player has quiet melee attacks. More...
 
bool block_hit (Creature *source, bodypart_id &bp_hit, damage_instance &dam) override
 Checks for valid block abilities and reduces damage accordingly. More...
 
item_location best_shield ()
 Returns the best item for blocking with. More...
 
bool handle_melee_wear (item_location shield, float wear_multiplier=1.0f)
 Calculates melee weapon wear-and-tear through use, returns true if item is destroyed. More...
 
matec_id pick_technique (Creature &t, const item_location &weap, bool crit, bool dodge_counter, bool block_counter, const std::vector< matec_id > &blacklist={})
 Returns a random valid technique. More...
 
std::vector< matec_idevaluate_techniques (Creature &t, const item_location &weap, bool crit=false, bool dodge_counter=false, bool block_counter=false, const std::vector< matec_id > &blacklist={})
 
void perform_technique (const ma_technique &technique, Creature &t, damage_instance &di, int &move_cost, item_location &cur_weapon)
 
damage_instance modify_damage_dealt_with_enchantments (const damage_instance &dam) const override
 
bool melee_attack (Creature &t, bool allow_special, const matec_id &force_technique, bool allow_unarmed=true, int forced_movecost=-1)
 Sets up a melee attack and handles melee attack function calls. More...
 
bool melee_attack_abstract (Creature &t, bool allow_special, const matec_id &force_technique, bool allow_unarmed=true, int forced_movecost=-1)
 
void reach_attack (const tripoint &p, int forced_movecost=-1)
 Handles reach melee attacks. More...
 
bool melee_attack (Creature &t, bool allow_special)
 Calls the to other melee_attack function with an empty technique id (meaning no specific technique should be used). More...
 
std::string melee_special_effects (Creature &t, damage_instance &d, item &weap)
 Handles combat effects, returns a string of any valid combat effect messages. More...
 
void perform_special_attacks (Creature &t, dealt_damage_instance &dealt_dam)
 Performs special attacks and their effects (poisonous, stinger, etc.) More...
 
std::vector< special_attackmutation_attacks (Creature &t) const
 Returns a vector of valid mutation attacks. More...
 
float bonus_damage (bool random) const
 Returns the bonus bashing damage the player deals based on their stats. More...
 
float get_melee_hit_base () const
 Returns weapon skill. More...
 
float hit_roll () const override
 Returns the player's basic hit roll that is compared to the target's dodge roll. More...
 
double crit_chance (float roll_hit, float target_dodge, const item &weap) const
 Returns the chance to critical given a hit roll and target's dodge roll. More...
 
bool scored_crit (float target_dodge, const item &weap) const
 Returns true if the player scores a critical hit. More...
 
int attack_speed (const item &weap) const
 Returns cost (in moves) of attacking with given item (no modifiers, like stuck) More...
 
int get_base_melee_stamina_cost (const item *weap=nullptr) const
 Returns cost (in stamina) of attacking with given item, or wielded item if nullptr (no modifiers, worst possible is -50) More...
 
int get_total_melee_stamina_cost (const item *weap=nullptr) const
 Returns total cost (in stamina) of attacking with given item, or wielded item if nullptr (modified by skill and walk/crouch/prone, worst possible is -50) More...
 
float get_hit_weapon (const item &weap) const
 Gets melee accuracy component from weapon+skills. More...
 
bool can_attack_high () const override
 Check if we can attack upper limbs. More...
 
double weapon_value (const item &weap, int ammo=10) const
 NPC-related item rating functions. More...
 
double gun_value (const item &weap, int ammo=10) const
 
double melee_value (const item &weap) const
 
double unarmed_value () const
 
dispersion_sources get_weapon_dispersion (const item &obj) const
 Returns a weapon's modified dispersion value. More...
 
void roll_all_damage (bool crit, damage_instance &di, bool average, const item &weap, const std::string &attack_vector, const Creature *target, const bodypart_id &bp) const
 Adds all 3 types of physical damage to instance. More...
 
void roll_damage (const damage_type_id &dt, bool crit, damage_instance &di, bool average, const item &weap, const std::string &attack_vector, float crit_mod) const
 
bool is_dead_state () const override
 Returns true if the player should be dead. More...
 
void set_part_hp_cur (const bodypart_id &id, int set) override
 
void mod_part_hp_cur (const bodypart_id &id, int set) override
 
void calc_all_parts_hp (float hp_mod=0.0, float hp_adjust=0.0, int str_max=0, int dex_max=0, int per_max=0, int int_max=0, int healthy_mod=0, int fat_to_max_hp=0)
 
bool is_stealthy () const
 Returns true if the player has stealthy movement. More...
 
bool can_melee () const
 Returns true if the current martial art works with the player's current weapon. More...
 
float stability_roll () const override
 Returns value of player's stable footing. More...
 
bool can_autolearn (const matype_id &ma_id) const
 Returns true if the player can learn the entered martial art. More...
 
bool practice (const skill_id &id, int amount, int cap=99, bool suppress_warning=false)
 This handles giving xp for a skill. More...
 
void handle_skill_warning (const skill_id &id, bool force_warning=false)
 This handles warning the player that there current activity will not give them xp. More...
 
ret_val< void > can_wield (const item &it) const
 Check player capable of wielding an item. More...
 
bool unwield ()
 
std::string weapname () const
 Get the formatted name of the currently wielded item (if any) with current gun mode (if gun) More...
 
std::string weapname_simple () const
 Get the formatted name of the currently wielded item (if any) without current gun mode and ammo. More...
 
std::string weapname_mode () const
 Get the formatted current gun mode (if gun) More...
 
std::string weapname_ammo () const
 Get the formatted current ammo (if gun) More...
 
void on_hit (Creature *source, bodypart_id bp_hit, float difficulty=INT_MIN, dealt_projectile_attack const *proj=nullptr) override
 Handles special defenses from melee attack that hit us (source can be null) More...
 
void did_hit (Creature &target)
 
void apply_damage (Creature *source, bodypart_id hurt, int dam, bool bypass_med=false) override
 Actually hurt the player, hurts a body_part directly, no armor reduction. More...
 
dealt_damage_instance deal_damage (Creature *source, bodypart_id bp, const damage_instance &d, const weakpoint_attack &attack=weakpoint_attack()) override
 Calls Creature::deal_damage and handles damaged effects (waking up, etc.) More...
 
int reduce_healing_effect (const efftype_id &eff_id, int remove_med, const bodypart_id &hurt)
 Reduce healing effect intensity, return initial intensity of the effect. More...
 
void cough (bool harmful=false, int loudness=4)
 
void passive_absorb_hit (const bodypart_id &bp, damage_unit &du) const
 Check for relevant passive, non-clothing that can absorb damage, and reduce by specified damage unit. More...
 
const weakpointabsorb_hit (const weakpoint_attack &attack, const bodypart_id &bp, damage_instance &dam) override
 Runs through all bionics and armor on a part and reduces damage through their armor_absorb. More...
 
float melee_weakpoint_skill (const item &weapon) const
 The character's skill in hitting a weakpoint. More...
 
float ranged_weakpoint_skill (const item &weapon) const
 
float throw_weakpoint_skill () const
 
bool armor_absorb (damage_unit &du, item &armor, const bodypart_id &bp, int roll) const
 Reduces and mutates du, prints messages about armor taking damage. More...
 
bool armor_absorb (damage_unit &du, item &armor, const bodypart_id &bp, const sub_bodypart_id &sbp, int roll) const
 Reduces and mutates du, prints messages about armor taking damage. More...
 
bool ablative_armor_absorb (damage_unit &du, item &armor, const sub_bodypart_id &bp, int roll)
 Reduces and mutates du, prints messages about armor taking damage. More...
 
void describe_damage (damage_unit &du, item &armor) const
 
float bionic_armor_bonus (const bodypart_id &bp, const damage_type_id &dt) const
 Check for passive bionics that provide armor, and returns the armor bonus This is called from player::passive_absorb_hit. More...
 
int mabuff_armor_bonus (const damage_type_id &type) const
 Returns the armor bonus against given type from martial arts buffs. More...
 
trait_id random_good_trait ()
 Returns the id of a random starting trait that costs >= 0 points. More...
 
trait_id random_bad_trait ()
 Returns the id of a random starting trait that costs < 0 points. More...
 
trait_id get_random_trait (const std::function< bool(const mutation_branch &)> &func)
 Returns the id of a random trait matching the given predicate. More...
 
void randomize_cosmetic_trait (const std::string &mutation_type)
 
bool has_conflicting_trait (const trait_id &flag) const
 Returns true if the player has a conflicting trait to the entered trait Uses has_opposite_trait(), has_lower_trait(), and has_higher_trait() to determine conflicts. More...
 
std::unordered_set< trait_idget_conflicting_traits (const trait_id &flag) const
 Returns all player's traits conflicting with the entered trait. More...
 
bool has_lower_trait (const trait_id &flag) const
 Returns true if the player has a trait which upgrades into the entered trait. More...
 
std::unordered_set< trait_idget_lower_traits (const trait_id &flag) const
 Returns player's traits which upgrade into the entered trait. More...
 
bool has_replacement_trait (const trait_id &flag) const
 Returns true if the player has a trait which is a replacement of the entered trait. More...
 
std::unordered_set< trait_idget_replacement_traits (const trait_id &flag) const
 Returns player's traits which replace the entered trait. More...
 
bool has_addition_trait (const trait_id &flag) const
 Returns true if the player has a trait which adds to the entered trait. More...
 
std::unordered_set< trait_idget_addition_traits (const trait_id &flag) const
 Returns player's traits which add to the entered trait. More...
 
bool has_same_type_trait (const trait_id &flag) const
 Returns true if the player has a trait that shares a type with the entered trait. More...
 
std::unordered_set< trait_idget_same_type_traits (const trait_id &flag) const
 Returns player's traits that share a type with the entered trait. More...
 
bool purifiable (const trait_id &flag) const
 Returns true if the entered trait may be purified away Defaults to true. More...
 
std::string get_category_dream (const mutation_category_id &cat, int strength) const
 Returns a dream's description selected randomly from the player's highest mutation category. More...
 
bool has_trait (const trait_id &b) const override
 Returns true if the player has the entered trait. More...
 
bool has_trait_variant (const trait_and_var &) const
 Returns true if the player has the entered trait with the desired variant. More...
 
bool has_base_trait (const trait_id &b) const
 Returns true if the player has the entered starting trait. More...
 
bool has_trait_flag (const json_character_flag &b) const
 Returns true if player has a trait with a flag. More...
 
bool has_bionic_with_flag (const json_character_flag &flag) const
 Returns true if player has a bionic with a flag. More...
 
bool has_bodypart_with_flag (const json_character_flag &flag) const
 Returns true if the player has any bodypart with a flag. More...
 
int count_trait_flag (const json_character_flag &b) const
 Returns count of traits with a flag. More...
 
int count_bionic_with_flag (const json_character_flag &flag) const
 Returns count of bionics with a flag. More...
 
int count_bodypart_with_flag (const json_character_flag &flag) const
 Returns count of bodyparts with a flag. More...
 
bool has_flag (const json_character_flag &flag) const
 Returns true if player has a trait, bionic, effect, bodypart, or martial arts buff with a flag. More...
 
int count_flag (const json_character_flag &flag) const
 Returns the count of traits, bionics, effects, bodyparts, and martial arts buffs with a flag. More...
 
trait_id trait_by_invlet (int ch) const
 Returns the trait id with the given invlet, or an empty string if no trait has that invlet. More...
 
void toggle_trait (const trait_id &, const std::string &="")
 Toggles a trait on the player and in their mutation list. More...
 
void set_mutations (const std::vector< trait_id > &traits)
 Add or removes a mutation on the player, but does not trigger mutation loss/gain effects. More...
 
void set_mutation (const trait_id &, const mutation_variant *=nullptr)
 
void set_mut_variant (const trait_id &, const mutation_variant *)
 Switches the variant of the given mutation, if the player has that mutation. More...
 
void do_mutation_updates ()
 
void unset_mutation (const trait_id &)
 
void switch_mutations (const trait_id &switched, const trait_id &target, bool start_powered, bool safe=false)
 Unset switched mutation and set target mutation instead, if safe mutates towards the target mutation. More...
 
bool can_power_mutation (const trait_id &mut) const
 
virtual void power_bionics ()
 Generates and handles the UI for player interaction with installed bionics. More...
 
bool can_interface_armor () const
 Check whether player has a bionic power armor interface. More...
 
virtual void power_mutations ()
 
void mutation_reflex_trigger (const trait_id &mut)
 Trigger reflex activation if the mutation has one. More...
 
void activate_mutation (const trait_id &mutation)
 
void deactivate_mutation (const trait_id &mut)
 
bool can_mount (const monster &critter) const
 
void mount_creature (monster &z)
 
bool cant_do_mounted (bool msg=true) const
 
bool is_mounted () const
 
bool check_mount_will_move (const tripoint &dest_loc)
 
bool check_mount_is_spooked ()
 
void dismount ()
 
void forced_dismount ()
 
bool move_in_vehicle (Creature *c, const tripoint &dest_loc) const
 Attempt to enter a tile in a vehicle. More...
 
bool is_deaf () const
 
bool is_mute () const
 
float get_limb_score (const limb_score_id &score, const body_part_type::type &bp=body_part_type::type::num_types, int override_encumb=-1, int override_wounds=-1) const
 
float manipulator_score (const std::map< bodypart_str_id, bodypart > &body, body_part_type::type type, int override_encumb, int override_wounds) const
 
bool has_min_manipulators () const
 
bool has_two_arms_lifting () const
 Returns true if the character has two functioning arms. More...
 
std::set< matec_idget_limb_techs () const
 
int get_working_arm_count () const
 
bool enough_working_legs () const
 Returns true if enough of your legs are working Currently requires all, new morphologies could be different. More...
 
int get_working_leg_count () const
 Returns the number of functioning legs. More...
 
bool is_limb_broken (const bodypart_id &limb) const
 Returns true if the limb is broken. More...
 
bool can_run () const
 source of truth of whether a Character can run More...
 
void hurtall (int dam, Creature *source, bool disturb=true)
 Hurts all body parts for dam, no armor reduction. More...
 
int hitall (int dam, int vary, Creature *source)
 Harms all body parts for dam, with armor reduction. More...
 
void on_hurt (Creature *source, bool disturb=true)
 Handles effects that happen when the player is damaged and aware of the fact. More...
 
void heal_bp (bodypart_id bp, int dam) override
 Heals a body_part for dam. More...
 
void heal (const bodypart_id &healed, int dam)
 Heals an part for dam. More...
 
void healall (int dam)
 Heals all body parts for dam. More...
 
std::vector< skill_idskills_offered_to (const Character *you) const
 
std::vector< proficiency_idproficiencies_offered_to (const Character *guy) const
 Proficiencies we know that the character doesn't. More...
 
std::vector< matype_idstyles_offered_to (const Character *you) const
 Martial art styles that we known, but the player p doesn't. More...
 
std::vector< spell_idspells_offered_to (const Character *you) const
 Spells that the NPC knows but that the player p doesn't. More...
 
int calc_spell_training_cost (bool knows, int difficulty, int level) const
 
void migrate_items_to_storage (bool disintegrate)
 used for profession spawning and save migration for nested containers. More...
 
bodypart_id body_window (const std::string &menu_header, bool show_all, bool precise, int normal_bonus, int head_bonus, int torso_bonus, int bleed, float bite, float infect, float bandage_power, float disinfectant_power) const
 Displays menu with body part hp, optionally with hp estimation after healing. More...
 
bool made_of (const material_id &m) const override
 
bool made_of_any (const std::set< material_id > &ms) const override
 
void calc_encumbrance ()
 Recalculate encumbrance for all body parts. More...
 
void calc_discomfort ()
 Calculate any discomfort your current clothes are causing. More...
 
void calc_encumbrance (const item &new_item)
 Recalculate encumbrance for all body parts as if new_item was also worn. More...
 
void recalculate_bodyparts ()
 
void recalculate_enchantment_cache ()
 
double calculate_by_enchantment (double modify, enchant_vals::mod value, bool round_output=false) const
 
bool has_mabuff (const mabuff_id &buff_id) const
 Returns true if the player has any martial arts buffs attached. More...
 
bool has_grab_break_tec () const override
 Returns true if the player has a grab breaking technique available. More...
 
float mabuff_tohit_bonus () const
 Returns the to hit bonus from martial arts buffs. More...
 
float mabuff_critical_hit_chance_bonus () const
 Returns the critical hit chance bonus from martial arts buffs. More...
 
float mabuff_dodge_bonus () const
 Returns the dodge bonus from martial arts buffs. More...
 
int mabuff_block_effectiveness_bonus () const
 Returns the blocking effectiveness bonus from martial arts buffs. More...
 
int mabuff_block_bonus () const
 Returns the block bonus from martial arts buffs. More...
 
int mabuff_speed_bonus () const
 Returns the speed bonus from martial arts buffs. More...
 
int mabuff_arpen_bonus (const damage_type_id &type) const
 Returns the arpen bonus from martial arts buffs. More...
 
float mabuff_damage_mult (const damage_type_id &type) const
 Returns the damage multiplier to given type from martial arts buffs. More...
 
int mabuff_damage_bonus (const damage_type_id &type) const
 Returns the flat damage bonus to given type from martial arts buffs, applied after the multiplier. More...
 
int mabuff_attack_cost_penalty () const
 Returns the flat penalty to move cost of attacks. More...
 
float mabuff_attack_cost_mult () const
 Returns the multiplier on move cost of attacks. More...
 
bool has_mabuff_flag (const json_character_flag &flag) const
 Returns true if player has a MA buff with a flag. More...
 
int count_mabuff_flag (const json_character_flag &flag) const
 
void mutation_effect (const trait_id &mut, bool worn_destroyed_override)
 Handles things like destruction of armor, etc. More...
 
void mutation_loss_effect (const trait_id &mut)
 Handles what happens when you lose a mutation. More...
 
bool has_active_mutation (const trait_id &b) const
 
time_duration get_cost_timer (const trait_id &mut_id) const
 
void set_cost_timer (const trait_id &mut, time_duration set)
 
void mod_cost_timer (const trait_id &mut, time_duration mod)
 
void mutate (const int &true_random_chance, bool use_vitamins)
 Picks a random valid mutation and gives it to the Character, possibly removing/changing others along the way. More...
 
void mutate ()
 
bool mutation_ok (const trait_id &mutation, bool allow_good, bool allow_bad, bool allow_neutral, const vitamin_id &mut_vit) const
 Returns true if the player doesn't have the mutation or a conflicting one and it complies with the allowed typing. More...
 
bool mutation_ok (const trait_id &mutation, bool allow_good, bool allow_bad, bool allow_neutral) const
 
bool roll_bad_mutation (const mutation_category_id &categ) const
 Roll, based on category and total mutations in/out of it, whether next mutation should be good or bad. More...
 
bool mutation_selector (const std::vector< trait_id > &prospective_traits, const mutation_category_id &cat, const bool &use_vitamins)
 Opens a menu which allows players to choose from a list of mutations. More...
 
void mutate_category (const mutation_category_id &mut_cat, bool use_vitamins, bool true_random=false)
 Picks a random valid mutation in a category and mutate_towards() it. More...
 
void mutate_category (const mutation_category_id &mut_cat)
 
bool mutate_towards (std::vector< trait_id > muts, const mutation_category_id &mut_cat, int num_tries=INT_MAX, bool use_vitamins=true, bool removed_base_trait=false)
 Mutates toward one of the given mutations, upgrading or removing conflicts if necessary. More...
 
bool mutate_towards (const trait_id &mut, const mutation_category_id &mut_cat, const mutation_variant *chosen_var=nullptr, bool use_vitamins=true, bool removed_base_trait=false)
 Mutates toward the entered mutation, upgrading or removing conflicts if necessary. More...
 
bool mutate_towards (const trait_id &mut, const mutation_variant *chosen_var=nullptr)
 
void remove_mutation (const trait_id &mut, bool silent=false)
 Removes a mutation, downgrading to the previous level if possible. More...
 
bool has_child_flag (const trait_id &flag) const
 Returns true if the player has the entered mutation child flag. More...
 
void remove_child_flag (const trait_id &flag)
 Removes the mutation's child flag from the player's list. More...
 
void test_crossing_threshold (const mutation_category_id &mutation_category)
 Try to cross The Threshold. More...
 
int mutation_height (const trait_id &mut) const
 Returns how many steps are required to reach a mutation. More...
 
void calc_mutation_levels ()
 Recalculates mutation_category_level[] values for the player. More...
 
weighted_int_list< mutation_category_idget_vitamin_weighted_categories () const
 Returns a weighted list of mutation categories based on blood vitamin levels. More...
 
void drench_mut_calc ()
 Recalculates mutation drench protection for all bodyparts (ignored/good/neutral stats) More...
 
bool is_category_allowed (const std::vector< mutation_category_id > &category) const
 Returns true if this category of mutation is allowed. More...
 
bool is_category_allowed (const mutation_category_id &category) const
 
bool can_use_heal_item (const item &med) const
 Check for mutation disallowing the use of an healing item. More...
 
bool can_install_cbm_on_bp (const std::vector< bodypart_id > &bps) const
 
resistances mutation_armor (bodypart_id bp) const
 Returns resistances on a body part provided by mutations. More...
 
float mutation_armor (bodypart_id bp, const damage_type_id &dt) const
 
float mutation_armor (bodypart_id bp, const damage_unit &du) const
 
void give_all_mutations (const mutation_category_trait &category, bool include_postthresh=false)
 gives every mutation in a category, optionally including post-thresh mutations More...
 
void unset_all_mutations ()
 unsets all mutations More...
 
bool activate_bionic (bionic &bio, bool eff_only=false, bool *close_bionics_ui=nullptr)
 Handles bionic activation effects of the entered bionic, returns if anything activated. More...
 
std::vector< bionic_idget_bionics () const
 
std::vector< const item * > get_pseudo_items () const
 
void invalidate_pseudo_items ()
 
void update_last_bionic_uid () const
 Finds the highest UID for installed bionics and caches the next valid UID. More...
 
bionic_uid generate_bionic_uid () const
 Returns the next valid UID for a bionic installation. More...
 
bool has_bionic (const bionic_id &b) const
 Returns true if the player has the entered bionic id. More...
 
bool has_active_bionic (const bionic_id &b) const
 Returns true if the player has the entered bionic id and it is powered on. More...
 
bool has_any_bionic () const
 Returns true if the player has any bionic. More...
 
std::vector< bionic_idget_bionic_fueled_with_muscle () const
 Return bionic_id of bionics able to use it as fuel. More...
 
std::vector< bionic_idget_fueled_bionics () const
 Return bionic_id of fueled bionics. More...
 
bionic_id get_remote_fueled_bionic () const
 Returns bionic_id of first remote fueled bionic found. More...
 
std::vector< item * > get_bionic_fuels (const bionic_id &bio)
 Return list of available fuel sources that are not empty for this bionic. More...
 
std::vector< item * > get_cable_ups ()
 Returns not-empty UPS connected to cable charger bionic. More...
 
std::vector< item * > get_cable_solar ()
 Returns solar items connected to cable charger bionic. More...
 
std::vector< vehicle * > get_cable_vehicle () const
 Returns vehicles connected to cable charger bionic. More...
 
bool is_using_bionic_weapon () const
 
bionic_uid get_weapon_bionic_uid () const
 
void process_bionic (bionic &bio)
 Handles bionic effects over time of the entered bionic. More...
 
ret_val< void > can_deactivate_bionic (bionic &bio, bool eff_only=false) const
 Checks if bionic can be deactivated (e.g. More...
 
bool deactivate_bionic (bionic &bio, bool eff_only=false)
 Handles bionic deactivation effects of the entered bionic, returns if anything deactivated. More...
 
void force_bionic_deactivation (bionic &bio)
 
int num_bionics () const
 Returns the size of my_bionics[]. More...
 
bionicbionic_at_index (int i)
 Returns the bionic at a given index in my_bionics[]. More...
 
void clear_bionics ()
 Remove all bionics. More...
 
int get_used_bionics_slots (const bodypart_id &bp) const
 
int get_total_bionics_slots (const bodypart_id &bp) const
 
int get_free_bionics_slots (const bodypart_id &bp) const
 
bool has_enough_anesth (const itype &cbm, Character &patient) const
 Has enough anesthetic for surgery. More...
 
bool has_enough_anesth (const itype &cbm) const
 
void consume_anesth_requirement (const itype &cbm, Character &patient)
 
bool has_installation_requirement (const bionic_id &bid) const
 Has the required equipment for manual installation. More...
 
void consume_installation_requirement (const bionic_id &bid)
 
void introduce_into_anesthesia (const time_duration &duration, Character &installer, bool needs_anesthesia)
 Handles process of introducing patient into anesthesia during Autodoc operations. More...
 
std::optional< bionic * > find_bionic_by_type (const bionic_id &b) const
 Finds the first bionic instance that matches the bionic_id. More...
 
std::optional< bionic * > find_bionic_by_uid (bionic_uid bio_uid) const
 Finds the bionic with specified UID. More...
 
void remove_bionic (const bionic &bio)
 Removes a bionic from my_bionics[]. More...
 
bionic_uid add_bionic (const bionic_id &b, bionic_uid parent_uid=0, bool suppress_debug=false)
 Adds a bionic to my_bionics[]. More...
 
float env_surgery_bonus (int radius) const
 Calculate skill bonus from tiles in radius. More...
 
float bionics_adjusted_skill (bool autodoc, int skill_level=-1) const
 Calculate skill for (un)installing bionics. More...
 
int bionics_pl_skill (bool autodoc, int skill_level=-1) const
 Calculate non adjusted skill for (un)installing bionics. More...
 
bool can_install_bionics (const itype &type, Character &installer, bool autodoc=false, int skill_level=-1) const
 Is the installation possible. More...
 
ret_val< void > is_installable (const item *it, bool by_autodoc) const
 Is this bionic elligible to be installed in the player? More...
 
std::map< bodypart_id, int > bionic_installation_issues (const bionic_id &bioid) const
 
bool install_bionics (const itype &type, Character &installer, bool autodoc=false, int skill_level=-1)
 Initialize all the values needed to start the operation player_activity. More...
 
void perform_install (const bionic_id &bid, bionic_uid upbio_uid, int difficulty, int success, int pl_skill, const std::string &installer_name, const std::vector< trait_id > &trait_to_rem, const tripoint &patient_pos)
 Success or failure of installation happens here. More...
 
void bionics_install_failure (const bionic_id &bid, const std::string &installer, int difficulty, int success, float adjusted_skill, const tripoint &patient_pos)
 
bool wield_contents (item &container, item *internal_item=nullptr, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY)
 Try to wield a contained item consuming moves proportional to weapon skill and volume. More...
 
void use (int inventory_position)
 Uses a tool. More...
 
void use (item_location loc, int pre_obtain_moves=-1, std::string const &method={})
 Uses a tool at location. More...
 
void use_wielded ()
 Uses the current wielded weapon. More...
 
std::optional< std::list< item >::iterator > wear (int pos, bool interactive=true)
 Wear item; returns false on fail. More...
 
std::optional< std::list< item >::iterator > wear (item_location item_wear, bool interactive=true)
 Wear item; returns false on fail. More...
 
trinary consume (item_location loc, bool force=false)
 Used for eating object at a location. More...
 
trinary consume (item &target, bool force=false)
 Used for eating a particular item that doesn't need to be in inventory. More...
 
void store (item &container, item &put, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY, pocket_type pk_type=pocket_type::CONTAINER, bool check_best_pkt=false)
 Stores an item inside another consuming moves proportional to weapon skill and volume. More...
 
void store (item_pocket *pocket, item &put, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY)
 
bool can_uninstall_bionic (const bionic &bio, Character &installer, bool autodoc=false, int skill_level=-1) const
 Is The uninstallation possible. More...
 
bool uninstall_bionic (const bionic &bio, Character &installer, bool autodoc=false, int skill_level=-1)
 Initialize all the values needed to start the operation player_activity. More...
 
void perform_uninstall (const bionic &bio, int difficulty, int success, int pl_skill)
 Success or failure of removal happens here. More...
 
void bionics_uninstall_failure (int difficulty, int success, float adjusted_skill)
 When a player fails the surgery. More...
 
void roll_critical_bionics_failure (const bodypart_id &bp)
 When a critical failure occurs. More...
 
bool uninstall_bionic (const bionic &bio, monster &installer, Character &patient, float adjusted_skill)
 Used by monster to perform surgery. More...
 
void bionics_uninstall_failure (monster &installer, Character &patient, int difficulty, int success, float adjusted_skill)
 When a monster fails the surgery. More...
 
void on_worn_item_transform (const item &old_it, const item &new_it)
 
bool gunmod_remove (item &gun, item &mod)
 Starts activity to remove gunmod after unloading any contained ammo. More...
 
void gunmod_add (item &gun, item &mod)
 Starts activity to install gunmod having warned user about any risk of failure or irremovable mods s. More...
 
void toolmod_add (item_location tool, item_location mod)
 Starts activity to install toolmod. More...
 
void mend_item (item_location &&obj, bool interactive=true)
 Attempt to mend an item (fix any current faults) More...
 
bool list_ammo (const item_location &base, std::vector< item::reload_option > &ammo_list, bool empty=true) const
 
void process_items ()
 
void leak_items ()
 
void search_surroundings ()
 Search surrounding squares for traps (and maybe other things in the future). More...
 
void heat_emission (const bionic &bio, units::energy fuel_energy)
 Handle heat from exothermic power generation. More...
 
float get_effective_efficiency (const bionic &bio, float fuel_efficiency) const
 Applies modifier to fuel_efficiency and returns the resulting efficiency. More...
 
units::energy get_power_level () const
 
units::energy get_max_power_level () const
 
void mod_power_level (const units::energy &npower)
 
void mod_max_power_level_modifier (const units::energy &npower_max)
 
void set_power_level (const units::energy &npower)
 
void set_max_power_level (const units::energy &capacity)
 
void set_max_power_level_modifier (const units::energy &capacity)
 
void update_bionic_power_capacity ()
 
bool is_max_power () const
 
bool has_power () const
 
bool has_max_power () const
 
bool enough_power_for (const bionic_id &bid) const
 
void disp_info (bool customize_character=false)
 Handles and displays detailed character info for the '@' screen. More...
 
void conduct_blood_analysis ()
 
bool is_worn (const item &thing) const
 
bool is_worn_module (const item &thing) const
 
virtual bool invoke_item (item *, const std::string &, const tripoint &pt, int pre_obtain_moves=-1)
 As above, but with a pre-selected method. More...
 
bool consume_charges (item &used, int qty)
 Consume charges of a tool or comestible item, potentially destroying it in the process. More...
 
item reduce_charges (item *it, int quantity)
 Remove charges from a specific item. More...
 
int item_handling_cost (const item &it, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY, int charges_in_it=-1, bool bulk_cost=false) const
 Calculate (but do not deduct) the number of moves required when handling (e.g. More...
 
int item_store_cost (const item &it, const item &container, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY) const
 Calculate (but do not deduct) the number of moves required when storing an item in a container. More...
 
int item_retrieve_cost (const item &it, const item &container, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY) const
 Calculate (but do not deduct) the number of moves required when drawing a weapon from an holster or sheathe. More...
 
int item_wear_cost (const item &it) const
 Calculate (but do not deduct) the number of moves required to wear an item. More...
 
std::optional< std::list< item >::iterator > wear_item (const item &to_wear, bool interactive=true, bool do_calc_encumbrance=true)
 Wear item; returns nullopt on fail, or pointer to newly worn item on success. More...
 
int amount_worn (const itype_id &id) const
 Returns the amount of item ‘type’ that is currently worn. More...
 
int count_softwares (const itype_id &id)
 Returns the amount of software ‘type’ that are in the inventory. More...
 
std::vector< item_locationnearby (const std::function< bool(const item *, const item *)> &func, int radius=1) const
 Returns nearby items which match the provided predicate. More...
 
std::list< itemremove_worn_items_with (const std::function< bool(item &)> &filter)
 Similar to remove_items_with, but considers only worn items and not their content (item::contents is not checked). More...
 
void clear_worn ()
 
std::vector< item_locationall_items_loc ()
 
std::vector< item_locationtop_items_loc ()
 
iteminvlet_to_item (int invlet) const
 Return the item pointer of the item with given invlet, return nullptr if the player does not have such an item with that invlet. More...
 
itemi_at (int position)
 
const itemi_at (int position) const
 
int get_item_position (const item *it) const
 Returns the item position (suitable for i_at or similar) of a specific item. More...
 
item_location used_weapon () const
 Returns a reference to the item which will be used to make attacks. More...
 
item_location used_weapon ()
 
item_location i_add (item it, bool should_stack=true, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_drop=true, bool allow_wield=true, bool ignore_pkt_settings=false)
 Adds the item to the character's worn items or wields it, or prompts if the Character cannot pick it up. More...
 
item_location i_add (item it, int &copies_remaining, bool should_stack=true, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_drop=true, bool allow_wield=true, bool ignore_pkt_settings=false)
 
item_location try_add (item it, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_wield=true, bool ignore_pkt_settings=false)
 tries to add to the character's inventory without a popup. More...
 
item_location try_add (item it, int &copies_remaining, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_wield=true, bool ignore_pkt_settings=false)
 
ret_val< item_locationi_add_or_fill (item &it, bool should_stack=true, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_drop=true, bool allow_wield=true, bool ignore_pkt_settings=false)
 
item i_rem (const item *it)
 Remove a specific item from player possession. More...
 
void i_rem_keep_contents (const item *it)
 
bool i_add_or_drop (item &it, int qty=1, const item *avoid=nullptr, const item *original_inventory_item=nullptr)
 Sets invlet and adds to inventory if possible, drops otherwise, returns true if either succeeded. More...
 
bool i_drop_at (item &it, int qty=1)
 Drops items at player location An optional qty can be provided (and will perform better than separate calls). More...
 
void handle_contents_changed (const std::vector< item_location > &containers)
 Check any already unsealed pockets in items pointed to by containers and propagate the unsealed status through the container tree. More...
 
std::bitset< std::numeric_limits< char >::max()> allocated_invlets () const
 Only use for UI things. More...
 
bool has_active_item (const itype_id &id) const
 Whether the player carries an active item of the given item type. More...
 
item remove_weapon ()
 
void remove_mission_items (int mission_id)
 
std::vector< const item * > get_ammo (const ammotype &at) const
 Returns the items that are ammo and have the matching ammo type. More...
 
std::vector< item_locationfind_ammo (const item &obj, bool empty=true, int radius=1) const
 Searches for ammo or magazines that can be used to reload obj. More...
 
std::vector< item_locationfind_reloadables ()
 Searches for weapons and magazines that can be reloaded. More...
 
int ammo_count_for (const item_location &gun) const
 Counts ammo and UPS charges (lower of) for a given gun on the character. More...
 
bool can_reload (const item &it, const item *ammo=nullptr) const
 Whether a tool or gun is potentially reloadable (optionally considering a specific ammo) More...
 
hint_rating rate_action_reload (const item &it) const
 Same as Character::can_reload, but checks for attached gunmods as well. More...
 
hint_rating rate_action_unload (const item &it) const
 Whether a tool or a gun can be unloaded. More...
 
hint_rating rate_action_insert (const item_location &loc) const
 
bool add_or_drop_with_msg (item &it, bool unloading=false, const item *avoid=nullptr, const item *original_inventory_item=nullptr)
 So far only called by unload() from game.cpp @avoid - do not put @it into @avoid @original_inventory_item set if the item was already in the characters inventory (wielded, worn, in different pocket) and is being moved. More...
 
bool unload (item_location &loc, bool bypass_activity=false, const item_location &new_container=item_location::nowhere)
 Unload item. More...
 
int item_reload_cost (const item &it, const item &ammo, int qty) const
 Calculate (but do not deduct) the number of moves required to reload an item with specified quantity of ammo. More...
 
projectile thrown_item_projectile (const item &thrown) const
 
int thrown_item_adjusted_damage (const item &thrown) const
 
int thrown_item_total_damage_raw (const item &thrown) const
 
int throw_range (const item &) const
 Maximum thrown range with a given item, taking all active effects into account. More...
 
int throwing_dispersion (const item &to_throw, Creature *critter=nullptr, bool is_blind_throw=false) const
 Dispersion of a thrown item, against a given target, taking into account whether or not the throw was blind. More...
 
int throw_dispersion_per_dodge (bool add_encumbrance=true) const
 How much dispersion does one point of target's dodge add when throwing at said target? More...
 
bool unarmed_attack () const
 True if unarmed. More...
 
units::mass best_nearby_lifting_assist () const
 Checks for items, tools, and vehicles with the Lifting quality near the character returning the largest weight liftable by an item in range. More...
 
units::mass best_nearby_lifting_assist (const tripoint &world_pos) const
 Alternate version if you need to specify a different origin point for nearby vehicle sources of lifting used for operations on distant objects (e.g. More...
 
std::vector< item * > inv_dump ()
 
std::vector< const item * > inv_dump () const
 
units::mass weight_carried () const
 
units::volume volume_carried () const
 
units::length max_single_item_length () const
 
units::volume max_single_item_volume () const
 
units::mass weight_carried_with_tweaks (const item_tweaks &tweaks) const
 
units::mass weight_carried_with_tweaks (const std::vector< std::pair< item_location, int >> &locations) const
 
units::volume volume_carried_with_tweaks (const item_tweaks &tweaks) const
 
units::volume volume_carried_with_tweaks (const std::vector< std::pair< item_location, int >> &locations) const
 
units::mass weight_capacity () const override
 
units::volume volume_capacity () const
 
units::volume volume_capacity_with_tweaks (const item_tweaks &tweaks) const
 
units::volume volume_capacity_with_tweaks (const std::vector< std::pair< item_location, int >> &locations) const
 
units::volume free_space () const
 
units::mass free_weight_capacity () const
 
units::volume holster_volume () const
 Returns the total volume of all worn holsters. More...
 
int used_holsters () const
 Used and total holsters. More...
 
int total_holsters () const
 
units::volume free_holster_volume () const
 
int empty_holsters () const
 
units::volume small_pocket_volume (const units::volume &threshold=1000_ml) const
 Returns the total volume of all pockets less than or equal to the volume passed in. More...
 
book_mastery get_book_mastery (const item &book) const
 
bool fun_to_read (const item &book) const
 Calculates the total fun bonus relative to this character's traits and chapter progress. More...
 
int book_fun_for (const item &book, const Character &p) const
 
bool can_pickVolume (const item &it, bool safe=false, const item *avoid=nullptr, bool ignore_pkt_settings=true) const
 
bool can_pickVolume_partial (const item &it, bool safe=false, const item *avoid=nullptr, bool ignore_pkt_settings=true, bool is_pick_up_inv=false) const
 
bool can_pickWeight (const item &it, bool safe=true) const
 
bool can_pickWeight_partial (const item &it, bool safe=true) const
 
std::pair< item_location, item_pocket * > best_pocket (const item &it, const item *avoid=nullptr, bool ignore_settings=false)
 What is the best pocket to put @it into? More...
 
std::vector< pocket_data_with_parentget_all_pocket_with_parent (const std::function< bool(const item_pocket *)> &filter=return_true< const item_pocket * >, const std::function< bool(const pocket_data_with_parent &a, const pocket_data_with_parent &b)> *sort_func=nullptr)
 Collect all pocket data (with parent and nest levels added) that the character has. More...
 
bool can_use (const item &it, const item &context=item()) const
 Checks if character stats and skills meet minimum requirements for the item. More...
 
ret_val< void > can_wear (const item &it, bool with_equip_change=false) const
 Check character capable of wearing an item. More...
 
bool is_armed () const
 Returns true if the character is wielding something. More...
 
bool has_wield_conflicts (const item &it) const
 Returns true if the character is wielding something and it can't be combined with the item passed as a parameter. More...
 
ret_val< void > can_unwield (const item &it) const
 Check player capable of unwielding an item. More...
 
ret_val< void > can_drop (const item &it) const
 Check player capable of dropping an item. More...
 
void clear_inventory_search_cache ()
 
void drop_invalid_inventory ()
 
void invalidate_inventory_validity_cache ()
 
void invalidate_weight_carried_cache ()
 
std::list< item * > get_dependent_worn_items (const item &it)
 Returns all items that must be taken off before taking off this item. More...
 
void drop (item_location loc, const tripoint &where)
 Drops an item to the specified location. More...
 
void pick_up (const drop_locations &what)
 Assigns character activity to pick up items from the given drop_locations. More...
 
bool is_wielding (const item &target) const
 
bool covered_with_flag (const flag_id &flag, const body_part_set &parts) const
 
bool is_waterproof (const body_part_set &parts) const
 
bool is_wearing (const itype_id &it) const
 Returns true if the player is wearing the item. More...
 
bool is_wearing_on_bp (const itype_id &it, const bodypart_id &bp) const
 Returns true if the player is wearing the item on the given body part. More...
 
bool worn_with_flag (const flag_id &flag, const bodypart_id &bp) const
 Returns true if the player is wearing an item with the given flag. More...
 
bool worn_with_flag (const flag_id &flag) const
 
item item_worn_with_flag (const flag_id &flag, const bodypart_id &bp) const
 Returns the first worn item with a given flag. More...
 
item item_worn_with_flag (const flag_id &flag) const
 
itemitem_worn_with_id (const itype_id &id)
 Returns pointer of the first worn item with a given id. More...
 
std::vector< std::pair< std::string, std::string > > get_overlay_ids () const
 Returns a list of the IDs of overlays on this character, sorted from "lowest" to "highest". More...
 
std::vector< std::pair< std::string, std::string > > get_overlay_ids_when_override_look () const
 Returns a list of the IDs of overlays on this character if the character has override look mutations sorted from "lowest" to "highest". More...
 
float get_skill_level (const skill_id &ident) const
 
float get_skill_level (const skill_id &ident, const item &context) const
 
int get_knowledge_level (const skill_id &ident) const
 
float get_knowledge_plus_progress (const skill_id &ident) const
 
int get_knowledge_level (const skill_id &ident, const item &context) const
 
float get_average_skill_level (const skill_id &ident) const
 
float get_greater_skill_or_knowledge_level (const skill_id &ident) const
 
SkillLevelMap get_all_skills () const
 
SkillLevelget_skill_level_object (const skill_id &ident)
 
const SkillLevelget_skill_level_object (const skill_id &ident) const
 
void set_skill_level (const skill_id &ident, int level)
 
void mod_skill_level (const skill_id &ident, int delta)
 
void set_knowledge_level (const skill_id &ident, int level)
 
void mod_knowledge_level (const skill_id &ident, int delta)
 
bool meets_skill_requirements (const std::map< skill_id, int > &req, const item &context=item()) const
 Checks whether the character's skills meet the required. More...
 
bool meets_skill_requirements (const construction &con) const
 Checks whether the character's skills meet the required. More...
 
bool meets_stat_requirements (const item &it) const
 Checks whether the character's stats meets the stats required by the item. More...
 
bool meets_requirements (const item &it, const item &context=item()) const
 Checks whether the character meets overall requirements to be able to use the item. More...
 
std::string enumerate_unmet_requirements (const item &it, const item &context=item()) const
 Returns a string of missed requirements (both stats and skills) More...
 
int read_speed () const
 Returns the player's reading speed as a percentage. More...
 
int lie_skill () const
 Returns a value used when attempting to convince NPC's of something false. More...
 
int persuade_skill () const
 Returns a value used when attempting to convince NPC's of something true. More...
 
int intimidation () const
 Returns a value used when attempting to intimidate NPC's. More...
 
void set_skills_from_hobbies ()
 
void set_bionics_from_hobbies ()
 
bool has_proficiency (const proficiency_id &prof) const
 
float get_proficiency_practice (const proficiency_id &prof) const
 
time_duration get_proficiency_practiced_time (const proficiency_id &prof) const
 
bool has_prof_prereqs (const proficiency_id &prof) const
 
void add_proficiency (const proficiency_id &prof, bool ignore_requirements=false)
 
void lose_proficiency (const proficiency_id &prof, bool ignore_requirements=false)
 
bool practice_proficiency (const proficiency_id &prof, const time_duration &amount, const std::optional< time_duration > &max=std::nullopt)
 
time_duration proficiency_training_needed (const proficiency_id &prof) const
 
void set_proficiency_practiced_time (const proficiency_id &prof, int turns)
 
std::vector< display_proficiencydisplay_proficiencies () const
 
std::vector< proficiency_idknown_proficiencies () const
 
std::vector< proficiency_idlearning_proficiencies () const
 
int get_proficiency_bonus (const std::string &category, proficiency_bonus_type prof_bonus) const
 
void add_default_background ()
 
void set_proficiencies_from_hobbies ()
 
void set_proficiency_practice (const proficiency_id &id, const time_duration &amount)
 
time_point get_time_died () const
 return the calendar::turn the character expired More...
 
void set_time_died (const time_point &time)
 set the turn the turn the character died if not already done More...
 
std::vector< spellspells_known_of_class (const trait_id &spell_class) const
 
bool cast_spell (spell &sp, bool fake_spell, const std::optional< tripoint > &target)
 
bool avoid_trap (const tripoint &pos, const trap &tr) const override
 Called when a player triggers a trap, returns true if they don't set it off. More...
 
bool add_faction_warning (const faction_id &id) const
 
int current_warnings_fac (const faction_id &id)
 
bool beyond_final_warning (const faction_id &id)
 
const Characterget_book_reader (const item &book, std::vector< std::string > &reasons) const
 Helper function for player::read. More...
 
time_duration time_to_read (const item &book, const Character &reader, const Character *learner=nullptr) const
 Helper function for get_book_reader. More...
 
read_condition_result check_read_condition (const item &book) const
 Helper function for get_book_reader. More...
 
void normalize () override
 Calls Creature::normalize() nulls out the player's weapon Should only be called through player::normalize(), not on it's own! More...
 
std::string get_name () const override
 
std::vector< std::string > get_grammatical_genders () const override
 
template<typename ... Args>
bool query_yn (const char *const msg, Args &&... args) const
 It is supposed to hide the query_yn to simplify player vs. More...
 
std::pair< bodypart_id, int > best_part_to_smash () const
 
bool check_immunity_data (const field_immunity_data &ft) const override
 
bool is_immune_field (const field_type_id &fid) const override
 Returns true if we are immune to the field type with the given fid. More...
 
bool is_elec_immune () const override
 Returns true is the player is protected from electric shocks. More...
 
bool is_immune_effect (const efftype_id &) const override
 Returns true if the player is immune to this kind of effect. More...
 
bool is_immune_damage (const damage_type_id &) const override
 Returns true if the player is immune to this kind of damage. More...
 
bool is_rad_immune () const
 Returns true if the player is protected from radiation. More...
 
bool is_knockdown_immune () const
 Returns true if the player is immune to knockdowns. More...
 
bool is_melee_bash_damage_cap_bonus () const
 Returns true if the player's melee skill increases the bash damage weapon cap. More...
 
bool immune_to (const bodypart_id &bp, damage_unit dam) const
 Check if a given body part is immune to a given damage type. More...
 
void mod_pain (int npain) override
 Modifies a pain value by player traits before passing it to Creature::mod_pain() More...
 
void set_pain (int npain) override
 Sets new intensity of pain an reacts to it. More...
 
int get_perceived_pain () const override
 Returns perceived pain (reduced with painkillers) More...
 
float fall_damage_mod () const override
 Returns multiplier on fall damage at low velocity (knockback/pit/1 z-level, not 5 z-levels) More...
 
int impact (int force, const tripoint &pos) override
 Deals falling/collision damage with terrain/creature at pos. More...
 
bool can_fly ()
 Checks to see if the character is able to use their wings properly. More...
 
void knock_back_to (const tripoint &to) override
 Knocks the player to a specified tile. More...
 
int hp_percentage () const override
 Returns overall % of HP remaining. More...
 
bool has_nv ()
 Returns true if the player has some form of night vision. More...
 
int get_lift_assist () const
 
float rest_quality () const
 Returns >0 if character is sitting/lying and relatively inactive. More...
 
float healing_rate (float at_rest_quality) const
 Average hit points healed per turn. More...
 
float healing_rate_medicine (float at_rest_quality, const bodypart_id &bp) const
 Average hit points healed per turn from healing effects. More...
 
social_modifiers get_mutation_bionic_social_mods () const
 Goes over all mutations/bionics, returning the sum of the social modifiers. More...
 
nc_color symbol_color () const override
 Creature symbol background color. More...
 
const std::string & symbol () const override
 Creature symbol. More...
 
std::string mutation_name (const trait_id &mut) const
 
std::string mutation_desc (const trait_id &mut) const
 
void empty_skills ()
 
void pick_name (bool bUseDefault=false)
 Returns a random name from NAMES_*. More...
 
std::vector< trait_idget_base_traits () const
 Get the idents of all base traits. More...
 
std::vector< trait_idget_mutations (bool include_hidden=true, bool ignore_enchantment=false, const std::function< bool(const mutation_branch &)> &filter=nullptr) const
 Get the idents of all traits/mutations. More...
 
std::vector< trait_and_varget_mutations_variants (bool include_hidden=true, bool ignore_enchantment=false) const
 Same as above, but also grab the variant ids (or empty string if none) More...
 
const std::bitset< NUM_VISION_MODES > & get_vision_modes () const
 
void clear_mutations ()
 Empties the trait and mutations lists. More...
 
void toggle_trait_deps (const trait_id &tr, const std::string &variant="")
 Steps through the dependency chain for the given trait. More...
 
void add_traits ()
 Adds mandatory scenario and profession traits unless you already have them And if you do already have them, refunds the points for the trait. More...
 
bool crossed_threshold () const
 Returns true if the player has crossed a mutation threshold Player can only cross one mutation threshold. More...
 
mutation_category_id get_threshold_category () const
 Returns the category that the player has crossed the threshold of, if they have one. More...
 
void environmental_revert_effect ()
 
int climbing_cost (const tripoint &from, const tripoint &to) const
 Checks both the neighborhoods of from and to for climbable surfaces, returns move cost of climbing from from to to. More...
 
bodypart_id most_staunchable_bp ()
 Which body part has the most staunchable bleeding, and what is the max improvement. More...
 
bodypart_id most_staunchable_bp (int &max)
 
void pause ()
 
template<typename T >
bool can_lift (const T &obj) const
 Check player strong enough to lift an object unaided by equipment (jacks, levers etc) More...
 
item_location get_wielded_item () const
 
item_location get_wielded_item ()
 
void set_wielded_item (const item &to_wield)
 
std::vector< matype_idknown_styles (bool teachable_only) const
 
bool has_martialart (const matype_id &m) const
 
int get_oxygen_max () const
 
bool can_recover_oxygen () const
 
void randomize_blood ()
 
void randomize_heartrate ()
 
int get_focus () const
 
void mod_focus (int amount)
 
void set_focus (int amount)
 
void queue_effect (const std::string &name, const time_duration &delay, const time_duration &duration)
 Queue an EOC to add effect after a delay. More...
 
int count_queued_effects (const std::string &effect) const
 Count queued add_effect EOCs for specific effect. More...
 
void add_addiction (const addiction_id &type, int strength)
 Adds an addiction to the player. More...
 
void rem_addiction (const addiction_id &type)
 Removes an addition from the player. More...
 
bool has_addiction (const addiction_id &type) const
 Returns true if the player has an addiction of the specified type. More...
 
int addiction_level (const addiction_id &type) const
 Returns the intensity of the specified addiction. More...
 
bool knows_creature_type (const Creature *c) const
 Returns true if the character is familiar with the given creature type. More...
 
bool knows_creature_type (const mtype_id &c) const
 Returns true if the character is familiar with the given creature type. More...
 
void set_knows_creature_type (const Creature *c)
 This character becomes familiar with creatures of the given type. More...
 
void set_knows_creature_type (const mtype_id &c)
 This character becomes familiar with creatures of the given type. More...
 
const std::set< mtype_id > & get_known_monsters () const
 Returns a list of all monster types known by this character. More...
 
void toggle_hauling ()
 
void start_hauling (const std::vector< item_location > &items_to_haul)
 
void stop_hauling ()
 
bool is_hauling () const
 
void start_autohaul ()
 
void stop_autohaul ()
 
bool is_autohauling () const
 
bool trim_haul_list (const std::vector< item_location > &valid_items)
 
void cache_visit_items_with (const itype_id &type, const std::function< void(item &)> &do_func)
 Applies a lambda function on all items with the given flag and/or that pass the given boolean item function, using or creating caches from inv_search_caches. More...
 
void cache_visit_items_with (const flag_id &type_flag, const std::function< void(item &)> &do_func)
 
void cache_visit_items_with (const std::string &key, bool(item::*filter_func)() const, const std::function< void(item &)> &do_func)
 
void cache_visit_items_with (const std::string &key, const itype_id &type, const flag_id &type_flag, bool(item::*filter_func)() const, const std::function< void(item &)> &do_func)
 
void cache_visit_items_with (const itype_id &type, const std::function< void(const item &)> &do_func) const
 
void cache_visit_items_with (const flag_id &type_flag, const std::function< void(const item &)> &do_func) const
 
void cache_visit_items_with (const std::string &key, bool(item::*filter_func)() const, const std::function< void(const item &)> &do_func) const
 
void cache_visit_items_with (const std::string &key, const itype_id &type, const flag_id &type_flag, bool(item::*filter_func)() const, const std::function< void(const item &)> &do_func) const
 
bool cache_has_item_with (const itype_id &type, const std::function< bool(const item &)> &check_func=return_true< item >) const
 Returns true if the character has an item with given flag and/or that passes the given boolean item function, using or creating caches from inv_search_caches. More...
 
bool cache_has_item_with (const flag_id &type_flag, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
bool cache_has_item_with (const std::string &key, bool(item::*filter_func)() const, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
bool cache_has_item_with (const std::string &key, const itype_id &type, const flag_id &type_flag, bool(item::*filter_func)() const, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
bool has_item_with_flag (const flag_id &flag, bool need_charges=false) const
 Find if the character has an item with a specific flag. More...
 
bool cache_has_item_with_flag (const flag_id &type_flag, bool need_charges=false) const
 Find if the character has an item whose type has a specific flag. More...
 
std::vector< item * > cache_get_items_with (const itype_id &type, const std::function< bool(item &)> &do_and_check_func=return_true< item >)
 Returns all items with the given flag and/or that pass the given boolean item function, using or creating caches from inv_search_caches. More...
 
std::vector< item * > cache_get_items_with (const flag_id &type_flag, const std::function< bool(item &)> &do_and_check_func=return_true< item >)
 
std::vector< item * > cache_get_items_with (const std::string &key, bool(item::*filter_func)() const, const std::function< bool(item &)> &do_and_check_func=return_true< item >)
 
std::vector< item * > cache_get_items_with (const std::string &key, const itype_id &type, const flag_id &type_flag, bool(item::*filter_func)() const, const std::function< bool(item &)> &do_and_check_func=return_true< item >)
 
std::vector< const item * > cache_get_items_with (const itype_id &type, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
std::vector< const item * > cache_get_items_with (const flag_id &type_flag, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
std::vector< const item * > cache_get_items_with (const std::string &key, bool(item::*filter_func)() const, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
std::vector< const item * > cache_get_items_with (const std::string &key, const itype_id &type, const flag_id &type_flag, bool(item::*filter_func)() const, const std::function< bool(const item &)> &check_func=return_true< item >) const
 
void add_to_inv_search_caches (item &it) const
 Add an item to existing inv_search_caches that it meets the criteria for. More...
 
bool has_charges (const itype_id &it, int quantity, const std::function< bool(const item &)> &filter=return_true< item >) const override
 
std::list< itemuse_amount (const itype_id &it, int quantity, const std::function< bool(const item &)> &filter=return_true< item >, bool select_ind=false)
 
bool use_charges_if_avail (const itype_id &it, int quantity)
 
units::energy available_ups () const
 Available ups from all sources Sum of mech, bionic UPS and UPS. More...
 
units::energy consume_ups (units::energy qty, int radius=-1)
 Consume UPS charges. More...
 
std::list< itemuse_charges (const itype_id &what, int qty, const std::function< bool(const item &)> &filter=return_true< item >)
 Use charges in character inventory. More...
 
std::list< itemuse_charges (const itype_id &what, int qty, int radius, const std::function< bool(const item &)> &filter=return_true< item >, bool in_tools=false)
 Use charges within a radius. More...
 
item find_firestarter_with_charges (int quantity) const
 
bool has_fire (int quantity) const
 
void use_fire (int quantity)
 
void assign_stashed_activity ()
 
bool check_outbounds_activity (const player_activity &act, bool check_only=false)
 
void assign_activity (const activity_id &type, int moves=calendar::INDEFINITELY_LONG, int index=-1, int pos=INT_MIN, const std::string &name="")
 
void assign_activity (const player_activity &act)
 Assigns activity to player, possibly resuming old activity if it's defined resumable. More...
 
void assign_activity (const activity_actor &actor)
 Assigns activity actor to player, possibly resuming old activity if it's defined resumable. More...
 
bool has_activity (const activity_id &type) const
 Check if player currently has a given activity. More...
 
bool has_activity (const std::vector< activity_id > &types) const
 Check if player currently has any of the given activities. More...
 
void resume_backlog_activity ()
 
void cancel_activity ()
 
void cancel_stashed_activity ()
 
player_activity get_stashed_activity () const
 
void set_stashed_activity (const player_activity &act, const player_activity &act_back=player_activity())
 
bool has_stashed_activity () const
 
bool can_stash (const item &it, bool ignore_pkt_settings=false)
 
bool can_stash (const item &it, int &copies_remaining, bool ignore_pkt_settings=false)
 
bool can_stash_partial (const item &it, bool ignore_pkt_settings=false)
 
void initialize_stomach_contents ()
 
float metabolic_rate_base () const
 Stable base metabolic rate due to traits. More...
 
float metabolic_rate () const
 Current metabolic rate due to traits, hunger, speed, etc. More...
 
int get_max_healthy () const
 
float get_bmi () const
 
float get_bmi_fat () const
 
float get_bmi_lean () const
 
int get_bmr () const
 
virtual void add_spent_calories (int)
 
virtual void add_gained_calories (int)
 
virtual void log_activity_level (float)
 
void reset_chargen_attributes ()
 
int base_age () const
 
void set_base_age (int age)
 
void mod_base_age (int mod)
 
int age (time_point when=calendar::turn) const
 
std::string age_string (time_point when=calendar::turn) const
 
int base_height () const
 
void set_base_height (int height)
 
void mod_base_height (int mod)
 
std::string height_string () const
 
int height () const
 
void randomize_height ()
 
units::mass bodyweight () const
 
units::mass bodyweight_lean () const
 
units::mass bodyweight_fat () const
 
float fat_ratio () const
 
units::mass bionics_weight () const
 
void set_activity_level (float new_level)
 
void decrease_activity_level (float new_level)
 
void reset_activity_level ()
 
std::string activity_level_str () const
 
int get_env_resist (bodypart_id bp) const override
 Returns overall env_resist on a body_part. More...
 
int get_armor_type (const damage_type_id &dt, bodypart_id bp) const override
 Returns overall resistance to given type on the bod part. More...
 
std::map< bodypart_id, int > get_all_armor_type (const damage_type_id &dt, const std::map< bodypart_id, std::vector< const item * >> &clothing_map) const
 
int get_stim () const
 
void set_stim (int new_stim)
 
void mod_stim (int mod)
 
int get_rad () const
 
void set_rad (int new_rad)
 
void mod_rad (int mod)
 
float get_heartrate_index () const
 
void set_heartrate_effect_mod (int mod)
 
void modify_heartrate_effect_mod (int mod)
 
int get_heartrate_effect_mod () const
 
void update_heartrate_index ()
 
float get_bloodvol_index () const
 
void update_bloodvol_index ()
 
float get_circulation_resistance () const
 
void set_bp_effect_mod (int mod)
 
void modify_bp_effect_mod (int mod)
 
int get_bp_effect_mod () const
 
void update_circulation_resistance ()
 
float get_respiration_rate () const
 
void set_respiration_effect_mod (int mod)
 
int get_respiration_effect_mod () const
 
void modify_respiration_effect_mod (int mod)
 
void update_respiration_rate ()
 
void update_circulation ()
 
int get_stamina () const
 
int get_stamina_max () const
 
void set_stamina (int new_stamina)
 
void burn_energy_arms (int mod)
 
void burn_energy_legs (int mod)
 
void burn_energy_all (int mod)
 
float get_bionic_limb_percentage () const
 
void mod_stamina (int mod)
 
void burn_move_stamina (int moves)
 
void update_stamina (int turns)
 Regenerates stamina. More...
 
int get_cardiofit () const
 
int get_cardio_acc () const
 
void set_cardio_acc (int ncardio_acc)
 
void reset_cardio_acc ()
 
int get_cardio_acc_base () const
 
bool handle_gun_damage (item &it)
 Returns true if a gun misfires, jams, or has other problems, else returns false. More...
 
bool handle_gun_overheat (item &it)
 Handles overheat mechanics for guns, returns true if the gun cant fire due to overheat effects. More...
 
double recoil_vehicle () const
 Get maximum recoil penalty due to vehicle motion. More...
 
double recoil_total () const
 Current total maximum recoil penalty from all sources. More...
 
int gun_engagement_moves (const item &gun, int target=0, int start=MAX_RECOIL, const Target_attributes &attributes=Target_attributes()) const
 How many moves does it take to aim gun to the target accuracy. More...
 
int fire_gun (const tripoint &target, int shots=1)
 Fires a gun or auxiliary gunmod (ignoring any current mode) More...
 
int fire_gun (const tripoint &target, int shots, item &gun)
 Fires a gun or auxiliary gunmod (ignoring any current mode) More...
 
dealt_projectile_attack throw_item (const tripoint &target, const item &to_throw, const std::optional< tripoint > &blind_throw_from_pos=std::nullopt)
 Execute a throw. More...
 
void on_item_wear (const item &it)
 Called when an item is worn. More...
 
void on_item_takeoff (const item &it)
 Called when an item is taken off. More...
 
void enchantment_wear_change ()
 
void on_worn_item_washed (const item &it)
 Called when an item is washed. More...
 
void on_item_acquire (const item &it)
 Called when an item is acquired (picked up, worn, or wielded) More...
 
void on_effect_int_change (const efftype_id &eid, int intensity, const bodypart_id &bp=bodypart_id("bp_null")) override
 Called when effect intensity has been changed. More...
 
void on_mutation_gain (const trait_id &mid)
 Called when a mutation is gained. More...
 
void on_mutation_loss (const trait_id &mid)
 Called when a mutation is lost. More...
 
void on_stat_change (const std::string &stat, int value) override
 Called when a stat is changed. More...
 
tripoint adjacent_tile () const
 Returns an unoccupied, safe adjacent point. More...
 
bool has_opposite_trait (const trait_id &flag) const
 Returns true if the player has a trait which cancels the entered trait. More...
 
std::unordered_set< trait_idget_opposite_traits (const trait_id &flag) const
 Returns traits that cancel the entered trait. More...
 
virtual void wake_up ()
 Removes "sleep" and "lying_down". More...
 
int get_shout_volume () const
 
void shout (std::string msg="", bool order=false)
 
void signal_nemesis ()
 
void vomit ()
 Handles Character vomiting effects. More...
 
void customize_appearance (customize_appearance_choice choice)
 
float adjust_for_focus (float amount) const
 
void update_type_of_scent (bool init=false)
 
void update_type_of_scent (const trait_id &mut, bool gain=true)
 
void set_type_of_scent (const scenttype_id &id)
 
scenttype_id get_type_of_scent () const
 
void restore_scent ()
 restore scent after masked_scent effect run out or is removed by water More...
 
void mod_painkiller (int npkill)
 Modifies intensity of painkillers
More...
 
void set_painkiller (int npkill)
 Sets intensity of painkillers
More...
 
int get_painkiller () const
 Returns intensity of painkillers
More...
 
void react_to_felt_pain (int intensity)
 
void clear_moncams ()
 Monster cameras are mtype_ids with an integer range of transmission. More...
 
void remove_moncam (const mtype_id &moncam_id)
 
void add_moncam (const std::pair< mtype_id, int > &moncam)
 
void set_moncams (std::map< mtype_id, int > nmoncams)
 
std::map< mtype_id, int > const & get_moncams () const
 
moncam_cache_t get_active_moncams () const
 
void spores ()
 
void blossoms ()
 
void rooted_message () const
 Handles rooting effects. More...
 
void rooted ()
 
void fall_asleep ()
 Adds "sleep" to the player. More...
 
void fall_asleep (const time_duration &duration)
 
std::string is_snuggling () const
 Checks to see if the player is using floor items to keep warm, and return the name of one such item if so. More...
 
ret_val< crush_tool_typecan_crush_frozen_liquid (item_location const &loc) const
 
bool crush_frozen_liquid (item_location loc)
 Prompts user about crushing item at item_location loc, for harvesting of frozen liquids. More...
 
float power_rating () const override
 Returns an approximation of the creature's strength. More...
 
bool sees_with_infrared (const Creature &critter) const
 Check whether the this player can see the other creature with infrared. More...
 
void place_corpse ()
 
void place_corpse (const tripoint_abs_omt &om_target)
 
std::vector< run_cost_effectrun_cost_effects (float &movecost) const
 Modifies the movement cost and returns a list of effects. More...
 
int run_cost (int base_cost, bool diag=false) const
 Returns the player's modified base movement cost. More...
 
std::vector< Creature * > get_hostile_creatures (int range) const
 Get all hostile creatures currently visible to this player. More...
 
std::vector< Creature * > get_visible_creatures (int range) const
 Returns all creatures that this player can see and that are in the given range. More...
 
std::vector< Creature * > get_targetable_creatures (int range, bool melee) const
 As above, but includes all creatures the player can detect well enough to target with ranged weapons, e.g. More...
 
int get_mutation_visibility_cap (const Character *observed) const
 Returns the mutation visibility threshold for the observer ( *this ) More...
 
std::string visible_mutations (int visibility_cap) const
 Returns an enumeration of visible mutations with colors. More...
 
player_activity get_destination_activity () const
 
void set_destination_activity (const player_activity &new_destination_activity)
 
void clear_destination_activity ()
 
bool can_use_pockets () const
 
bool can_use_hood () const
 
bool can_use_collar () const
 
std::map< bodypart_id, int > bonus_item_warmth () const
 Returns warmth provided by an armor's bonus, like hoods, pockets, etc. More...
 
bool can_use_floor_warmth () const
 Can the player lie down and cover self with blankets etc. More...
 
units::temperature_delta floor_warmth (const tripoint &pos) const
 Final warmth from the floor. More...
 
units::temperature_delta bodytemp_modifier_traits (bool overheated) const
 Correction factor of the body temperature due to traits and mutations. More...
 
units::temperature temp_corrected_by_climate_control (units::temperature temperature, int heat_strength, int chill_strength) const
 Value of the body temperature corrected by climate control. More...
 
bool in_sleep_state () const override
 
void update_vitamins (const vitamin_id &vit)
 Set vitamin deficiency/excess disease states dependent upon current vitamin levels. More...
 
int vitamin_get (const vitamin_id &vit) const
 Check current level of a vitamin. More...
 
int get_daily_vitamin (const vitamin_id &vit, bool actual=true) const
 
void vitamin_set (const vitamin_id &vit, int qty)
 Sets level of a vitamin. More...
 
int vitamin_mod (const vitamin_id &vit, int qty)
 Add or subtract vitamins from character storage pools. More...
 
void vitamins_mod (const std::map< vitamin_id, int > &)
 
time_duration vitamin_rate (const vitamin_id &vit) const
 Get vitamin usage rate (minutes per unit) accounting for bionics, mutations and effects. More...
 
std::map< vitamin_id, int > effect_vitamin_mod (const std::map< vitamin_id, int > &)
 Modify vitamin intake (e.g. More...
 
void clear_vitamins ()
 Remove all vitamins. More...
 
void reset_daily_vitamin (const vitamin_id &vit)
 
int nutrition_for (const item &comest) const
 Handles the nutrition value for a comestible. More...
 
ret_val< edible_ratingcan_eat (const item &food) const
 Can the food be [theoretically] eaten no matter the consequences? More...
 
ret_val< edible_ratingwill_eat (const item &food, bool interactive=false) const
 Same as can_eat, but takes consequences into account. More...
 
int get_acquirable_energy (const item &it) const
 Determine character's capability of recharging their CBMs. More...
 
void modify_stimulation (const islot_comestible &comest)
 Used to apply stimulation modifications from food and medication. More...
 
void modify_sleepiness (const islot_comestible &comest)
 Used to apply sleepiness modifications from food and medication. More...
 
void modify_radiation (const islot_comestible &comest)
 
void modify_addiction (const islot_comestible &comest)
 Used to apply addiction modifications from food and medication. More...
 
void modify_health (const islot_comestible &comest)
 Used to apply health modifications from food and medication. More...
 
double compute_effective_food_volume_ratio (const item &food) const
 Used to compute how filling a food is. More...
 
units::volume masticated_volume (const item &food) const
 Used to calculate dry volume of a chewed food. More...
 
int compute_calories_per_effective_volume (const item &food, const nutrients *nutrient=nullptr) const
 Used to to display how filling a food is. More...
 
bool consume_effects (item &food)
 Handles the effects of consuming an item. More...
 
bool can_consume_as_is (const item &it) const
 Check whether the character can consume this very item. More...
 
bool can_estimate_rot () const
 True if the character has enough skill (in cooking or survival) to estimate time to rot. More...
 
itemget_consumable_from (item &it) const
 Returns a reference to the item itself (if it's consumable), the first of its contents (if it's consumable) or null item otherwise. More...
 
std::pair< nutrients, nutrientscompute_nutrient_range (const item &, const recipe_id &, std::map< recipe_id, std::pair< nutrients, nutrients >> &rec_cache, const cata::flat_set< flag_id > &extra_flags={}) const
 Get calorie & vitamin contents for a comestible, taking into account character traits. More...
 
std::pair< nutrients, nutrientscompute_nutrient_range (const itype_id &, std::map< recipe_id, std::pair< nutrients, nutrients >> &rec_cache, const cata::flat_set< flag_id > &extra_flags={}) const
 Same, but across arbitrary recipes. More...
 
morale_type allergy_type (const item &food) const
 Returns allergy type or MORALE_NULL if not allergic for this character. More...
 
nutrients compute_effective_nutrients (const item &) const
 
bool wearing_something_on (const bodypart_id &bp) const
 Returns true if the character is wearing something on the entered body part. More...
 
bool wearing_fitting_on (const bodypart_id &bp) const
 Returns true if the character is wearing something on the entered body part. More...
 
double armwear_factor () const
 Same as footwear factor, but for arms. More...
 
int shoe_type_count (const itype_id &it) const
 Returns 1 if the player is wearing an item of that count on one foot, 2 if on both, and zero if on neither. More...
 
bool is_wearing_shoes (const side &check_side=side::BOTH) const
 Returns true if the player is wearing something on their feet that is not SKINTIGHT. More...
 
bool is_barefoot () const
 Returns true if the player is not wearing anything that covers the soles of their feet, ignoring INTEGRATED. More...
 
bool is_worn_item_visible (std::list< item >::const_iterator) const
 Returns true if the worn item is visible (based on layering and coverage) More...
 
std::list< itemget_visible_worn_items () const
 Returns all worn items visible to an outside observer. More...
 
bool change_side (item &it, bool interactive=true)
 Swap side on which item is worn; returns false on fail. More...
 
bool change_side (item_location &loc, bool interactive=true)
 
bool get_check_encumbrance () const
 
void set_check_encumbrance (bool new_check)
 
void update_morale ()
 Ticks down morale counters and removes them. More...
 
void apply_persistent_morale ()
 Ensures persistent morale effects are up-to-date. More...
 
void hoarder_morale_penalty ()
 
void modify_morale (item &food, int nutr=0)
 Used to apply morale modifications from food and medication. More...
 
int get_morale_level () const
 
void add_morale (const morale_type &type, int bonus, int max_bonus=0, const time_duration &duration=1_hours, const time_duration &decay_start=30_minutes, bool capped=false, const itype *item_type=nullptr)
 
int has_morale (const morale_type &type) const
 
void rem_morale (const morale_type &type, const itype *item_type=nullptr)
 
void clear_morale ()
 
bool has_morale_to_read () const
 
bool has_morale_to_craft () const
 
const inventorycrafting_inventory (bool clear_path) const
 
const inventorycrafting_inventory (const tripoint &src_pos=tripoint_zero, int radius=PICKUP_RANGE, bool clear_path=true) const
 Returns items that can be used to craft with. More...
 
void invalidate_crafting_inventory ()
 
float fine_detail_vision_mod (const tripoint &p=tripoint_min) const
 Returns a value from 1.0 to 11.0 that acts as a multiplier for the time taken to perform tasks that require detail vision, above 4.0 means these activities cannot be performed. More...
 
void make_craft_with_command (const recipe_id &id_to_make, int batch_size, bool is_long, const std::optional< tripoint > &loc)
 
bool has_recipe (const recipe *r) const
 
bool knows_recipe (const recipe *rec) const
 
void learn_recipe (const recipe *rec)
 
void forget_recipe (const recipe *rec)
 
void forget_all_recipes ()
 
int exceeds_recipe_requirements (const recipe &rec) const
 
bool has_recipe_requirements (const recipe &rec) const
 
bool can_decomp_learn (const recipe &rec) const
 
bool studied_all_recipes (const itype &book) const
 
const recipe_subsetget_learned_recipes () const
 Returns all known recipes. More...
 
recipe_subset get_available_nested (const recipe_subset &) const
 
recipe_subset get_recipes_from_books (const inventory &crafting_inv) const
 Returns all recipes that are known from the books (either in inventory or nearby). More...
 
recipe_subset get_recipes_from_ebooks (const inventory &crafting_inv) const
 Returns all recipes that are known from the books inside ereaders (either in inventory or nearby). More...
 
recipe_subset get_group_available_recipes () const
 Return all available recipes for any member of this crafter's group. More...
 
std::set< itype_idget_books_for_recipe (const inventory &crafting_inv, const recipe *r) const
 Returns the set of book types in crafting_inv that provide the given recipe. More...
 
float morale_crafting_speed_multiplier (const recipe &rec) const
 
float lighting_craft_speed_multiplier (const recipe &rec, const tripoint &p=tripoint_min) const
 
float crafting_speed_multiplier (const recipe &rec) const
 
float workbench_crafting_speed_multiplier (const item &craft, const std::optional< tripoint > &loc) const
 
float crafting_speed_multiplier (const item &craft, const std::optional< tripoint > &loc, bool use_cached_workbench_multiplier=false, float cached_workbench_multiplier=0.0f) const
 For use with in progress crafts. More...
 
int available_assistant_count (const recipe &rec) const
 
int64_t expected_time_to_craft (const recipe &rec, int batch_size=1) const
 Expected time to craft a recipe, with assumption that multipliers stay constant. More...
 
std::vector< const item * > get_eligible_containers_for_crafting () const
 
bool check_eligible_containers_for_crafting (const recipe &rec, int batch_size=1) const
 
bool can_make (const recipe *r, int batch_size=1) const
 
bool can_start_craft (const recipe *rec, recipe_filter_flags, int batch_size=1) const
 Returns true if the player can start crafting the recipe with the given batch size The player is not required to have enough tool charges to finish crafting, only to complete the first step (total / 20 + total % 20 charges) More...
 
bool making_would_work (const recipe_id &id_to_make, int batch_size) const
 
void craft (const std::optional< tripoint > &loc=std::nullopt, const recipe_id &goto_recipe=recipe_id(), const std::string &filterstring="")
 Start various types of crafts. More...
 
void recraft (const std::optional< tripoint > &loc=std::nullopt)
 
void long_craft (const std::optional< tripoint > &loc=std::nullopt, const recipe_id &goto_recipe=recipe_id())
 
void make_craft (const recipe_id &id, int batch_size, const std::optional< tripoint > &loc=std::nullopt)
 
void make_all_craft (const recipe_id &id, int batch_size, const std::optional< tripoint > &loc)
 
void start_craft (craft_command &command, const std::optional< tripoint > &loc)
 consume components and create an active, in progress craft containing them More...
 
float crafting_success_roll (const recipe &making) const
 Calculate a value representing the success of the player at crafting the given recipe, taking player skill, recipe difficulty, npc helpers, and player mutations into account. More...
 
float crafting_failure_roll (const recipe &making) const
 
float get_recipe_weighted_skill_average (const recipe &making) const
 
float recipe_success_chance (const recipe &making) const
 
float item_destruction_chance (const recipe &making) const
 
craft_roll_data recipe_success_roll_data (const recipe &making) const
 
craft_roll_data recipe_failure_roll_data (const recipe &making) const
 
void complete_craft (item &craft, const std::optional< tripoint > &loc)
 
bool can_continue_craft (item &craft)
 Check if the player meets the requirements to continue the in progress craft and if unable to continue print messages explaining the reason. More...
 
bool can_continue_craft (item &craft, const requirement_data &continue_reqs)
 
std::vector< Character * > get_crafting_helpers () const
 Return nearby Characters ready and willing to help with crafting. More...
 
std::vector< Character * > get_crafting_group () const
 Return group of ally characters sharing knowledge of crafting. More...
 
int get_num_crafting_helpers (int max) const
 
bool craft_skill_gain (const item &craft, const int &num_practice_ticks)
 Handle skill gain for player and followers during crafting. More...
 
bool craft_proficiency_gain (const item &craft, const time_duration &time)
 Handle proficiency practice for player and followers while crafting. More...
 
ret_val< void > can_disassemble (const item &obj, const read_only_visitable &inv) const
 Check if the player can disassemble an item using the current crafting inventory. More...
 
item_location create_in_progress_disassembly (item_location target)
 
bool disassemble ()
 
bool disassemble (item_location target, bool interactive=true, bool disassemble_all=false)
 
void disassemble_all (bool one_pass)
 
void complete_disassemble (item_location target)
 Completely disassemble an item, and drop yielded components at its former position. More...
 
void complete_disassemble (item_location &target, const recipe &dis)
 
const requirement_dataselect_requirements (const std::vector< const requirement_data * > &, int batch, const read_only_visitable &, const std::function< bool(const item &)> &filter) const
 
comp_selection< item_compselect_item_component (const std::vector< item_comp > &components, int batch, read_only_visitable &map_inv, bool can_cancel=false, const std::function< bool(const item &)> &filter=return_true< item >, bool player_inv=true, bool npc_query=false, const recipe *rec=nullptr)
 
std::list< itemconsume_items (const comp_selection< item_comp > &is, int batch, const std::function< bool(const item &)> &filter=return_true< item >, bool select_ind=false)
 
std::list< itemconsume_items (map &m, const comp_selection< item_comp > &is, int batch, const std::function< bool(const item &)> &filter=return_true< item >, const std::vector< tripoint > &reachable_pts={}, bool select_ind=false)
 
std::list< itemconsume_items (const std::vector< item_comp > &components, int batch=1, const std::function< bool(const item &)> &filter=return_true< item >, const std::function< bool(const itype_id &)> &select_ind=return_false< itype_id >)
 
bool consume_software_container (const itype_id &software_id)
 
comp_selection< tool_compselect_tool_component (const std::vector< tool_comp > &tools, int batch, read_only_visitable &map_inv, bool can_cancel=false, bool player_inv=true, bool npc_query=false, const std::function< int(int)> &charges_required_modifier=[](int i) { return i;})
 
bool craft_consume_tools (item &craft, int multiplier, bool start_craft)
 Consume tools for the next multiplier * 5% progress of the craft. More...
 
void consume_tools (const comp_selection< tool_comp > &tool, int batch)
 
void consume_tools (map &m, const comp_selection< tool_comp > &tool, int batch, const tripoint &origin=tripoint_zero, int radius=PICKUP_RANGE, basecamp *bcp=nullptr)
 
void consume_tools (map &m, const comp_selection< tool_comp > &tool, int batch, const std::vector< tripoint > &reachable_pts={}, basecamp *bcp=nullptr)
 
void consume_tools (const std::vector< tool_comp > &tools, int batch=1)
 
void check_and_recover_morale ()
 Checks permanent morale for consistency and recovers it when an inconsistency is found. More...
 
std::pair< int, int > fun_for (const item &comest, bool ignore_already_ate=false) const
 Handles the enjoyability value for a comestible. More...
 
void suffer ()
 Handles a large number of timers decrementing and other randomized effects. More...
 
bool irradiate (float rads, bool bypass=false)
 Handles mitigation and application of radiation. More...
 
void mend (int rate_multiplier)
 Handles the chance for broken limbs to spontaneously heal to 1 HP. More...
 
float get_leak_level () const
 
void calculate_leak_level ()
 Iterate through the character inventory to get its leak level. More...
 
void invalidate_leak_level_cache ()
 Sets leak_level_dirty to true. More...
 
void sound_hallu ()
 Creates an auditory hallucination. More...
 
void echo_pulse ()
 All nearby obstacles make a very quiet sound. More...
 
bool is_driving () const
 Checks if a Character is driving. More...
 
void drench (int saturation, const body_part_set &flags, bool ignore_waterproof)
 Drenches the player with water, saturation is the percent gotten wet. More...
 
void apply_wetness_morale (units::temperature temperature)
 Recalculates morale penalty/bonus from wetness based on mutations, equipment and temperature. More...
 
int heartrate_bpm () const
 
std::vector< std::string > short_description_parts () const
 
std::string short_description () const
 
bool can_hear (const tripoint &source, int volume) const
 
float hearing_ability () const
 
bool knows_trap (const tripoint &pos) const
 
void add_known_trap (const tripoint &pos, const trap &t)
 
bool sees (const tripoint &t, bool is_avatar=false, int range_mod=0) const override
 
bool sees (const tripoint_bub_ms &t, bool is_avatar=false, int range_mod=0) const override
 
bool sees (const Creature &critter) const override
 
int get_lowest_hp () const
 
bool has_weapon () const override
 
void shift_destination (const point &shift)
 
void set_destination (const std::vector< tripoint_bub_ms > &route, const player_activity &new_destination_activity=player_activity())
 
void clear_destination ()
 
bool has_distant_destination () const
 
bool is_auto_moving () const
 
bool has_destination () const
 
bool has_destination_activity () const
 
void start_destination_activity ()
 
std::vector< tripoint_bub_ms > & get_auto_move_route ()
 
action_id get_next_auto_move_direction ()
 
bool defer_move (const tripoint &next)
 
time_duration get_consume_time (const item &it) const
 
std::pair< int, int > weariness_transition_progress () const
 
int weariness_level () const
 
int weariness_transition_level () const
 
int weary_threshold () const
 
int weariness () const
 
float activity_level () const
 
float instantaneous_activity_level () const
 Returns instantaneous activity level as a float from 0-10 (from game_constants) More...
 
int activity_level_index () const
 Returns instantaneous activity level as an int from 0-5 (half of instantaneous_activity_level) More...
 
float exertion_adjusted_move_multiplier (float level=-1.0f) const
 
float maximum_exertion_level () const
 
std::string activity_level_str (float level) const
 
std::string debug_weary_info () const
 
void add_pain_msg (int, const bodypart_id &) const
 
double vomit_mod ()
 Returns the modifier value used for vomiting effects. More...
 
bool can_sleep ()
 Checked each turn during "lying_down", returns true if the player falls asleep. More...
 
int sleep_spot (const tripoint_bub_ms &p) const
 Rate point's ability to serve as a bed. More...
 
void process_effects () override
 Processes human-specific effects of effects before calling Creature::process_effects(). More...
 
void hardcoded_effects (effect &it)
 Handles the still hard-coded effects. More...
 
time_duration estimate_effect_dur (const skill_id &relevant_skill, const efftype_id &effect, const time_duration &error_magnitude, const time_duration &minimum_error, int threshold, const Creature &target) const
 Estimate effect duration based on player relevant skill. More...
 
itembest_item_with_quality (const quality_id &qid)
 Look for items in the player's inventory that have the specified quality; return the one with highest level. More...
 
bool has_quality (const quality_id &qual, int level=1, int qty=1) const override
 Returns true if instance has amount (or more) items of at least quality level. More...
 
int max_quality (const quality_id &qual) const override
 Return maximum tool quality level provided by instance or INT_MIN if not found. More...
 
int max_quality (const quality_id &qual, int radius) const
 
VisitResponse visit_items (const std::function< VisitResponse(item *, item *)> &func) const override
 Traverses this object and any child items contained using a visitor pattern. More...
 
std::list< itemremove_items_with (const std::function< bool(const item &)> &filter, int count=INT_MAX) override
 Removes items contained by this instance which match the filter. More...
 
int charges_of (const itype_id &what, int limit=INT_MAX, const std::function< bool(const item &)> &filter=return_true< item >, const std::function< void(int)> &visitor=nullptr, bool in_tools=false) const override
 Count maximum available charges from this instance and any contained items. More...
 
int amount_of (const itype_id &what, bool pseudo=true, int limit=INT_MAX, const std::function< bool(const item &)> &filter=return_true< item >) const override
 Count items matching id including both this instance and any contained items. More...
 
std::pair< int, int > kcal_range (const itype_id &id, const std::function< bool(const item &)> &filter, Character &player_character) const
 
int base_bmr () const
 
void store (JsonOut &json) const
 Load variables from json into object. More...
 
void load (const JsonObject &data)
 Gather variables for saving. More...
 
int vitamin_RDA (const vitamin_id &vitamin, int ammount) const
 Returns the % of your RDA that ammount of vitamin represents. More...
 
void process_one_effect (effect &it, bool is_new) override
 Processes human-specific effects of an effect. More...
 
std::map< bodypart_id, float > bodypart_exposure ()
 Map body parts to their total exposure, from 0.0 (fully covered) to 1.0 (buck naked). More...
 
virtual void mod_speed_bonus (int nspeed)
 Setters for stats shared with other creatures. More...
 
virtual void add_msg_if_player (const std::string &) const
 
virtual void add_msg_if_player (const game_message_params &, const std::string &) const
 
void add_msg_if_player (const translation &) const
 
void add_msg_if_player (const game_message_params &, const translation &) const
 
template<typename ... Args>
void add_msg_if_player (const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const translation &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const translation &msg, Args &&... args) const
 
virtual void add_msg_player_or_npc (const std::string &, const std::string &) const
 
virtual void add_msg_player_or_npc (const game_message_params &, const std::string &, const std::string &) const
 
void add_msg_player_or_npc (const translation &, const translation &) const
 
void add_msg_player_or_npc (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_npc (const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
virtual void add_msg_player_or_say (const std::string &, const std::string &) const
 
virtual void add_msg_player_or_say (const game_message_params &, const std::string &, const std::string &) const
 
void add_msg_player_or_say (const translation &, const translation &) const
 
void add_msg_player_or_say (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_say (const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
virtual bool has_flag (const mon_flag_id &) const
 This is to prevent clang complaining about overloading a virtual function, the creature version uses monster flags so confusion is unlikely. More...
 
bool pour_into (item_location &container, item &liquid, bool ignore_settings)
 Try to pour the given liquid into the given container/vehicle. More...
 
bool pour_into (const vpart_reference &vp, item &liquid) const
 
- Public Member Functions inherited from Creature
 ~Creature () override
 
virtual bool is_monster () const
 
virtual avataras_avatar ()
 
virtual const avataras_avatar () const
 
virtual monsteras_monster ()
 
virtual const monsteras_monster () const
 
virtual bool is_fake () const
 Returns true for non-real Creatures used temporarily; i.e. More...
 
virtual void set_fake (bool fake_value)
 Sets a Creature's fake boolean. More...
 
tripoint pos () const
 
tripoint_bub_ms pos_bub () const
 
int posx () const
 
int posy () const
 
int posz () const
 
void setpos (const tripoint &p)
 
void move_to (const tripoint_abs_ms &loc)
 Moves the creature to the given location and calls the on_move() handler. More...
 
virtual void bleed () const
 Adds an appropriate blood splatter. More...
 
bool sees (const Creature &critter) const override
 The functions check whether this creature can see the target. More...
 
bool sees (const tripoint &t, bool is_avatar=false, int range_mod=0) const override
 
bool sees (const tripoint_bub_ms &t, bool is_avatar=false, int range_mod=0) const override
 
Creatureauto_find_hostile_target (int range, int &boo_hoo, int area=0)
 For fake-players (turrets, mounted turrets) this functions chooses a target. More...
 
double ranged_target_size () const
 Size of the target this creature presents to ranged weapons. More...
 
void knock_back_from (const tripoint &p)
 
float get_crit_factor (const bodypart_id &bp) const
 
int size_melee_penalty () const
 
virtual int deal_melee_attack (Creature *source, int hitroll)
 
bool is_adjacent (const Creature *target, bool allow_z_levels) const
 
virtual void deal_melee_hit (Creature *source, int hit_spread, bool critical_hit, damage_instance dam, dealt_damage_instance &dealt_dam, const weakpoint_attack &attack=weakpoint_attack(), const bodypart_id *bp=nullptr)
 
virtual void deal_projectile_attack (Creature *source, dealt_projectile_attack &attack, bool print_messages=true, const weakpoint_attack &wp_attack=weakpoint_attack())
 Attempts to harm a creature with a projectile. More...
 
virtual void deal_damage_handle_type (const effect_source &source, const damage_unit &du, bodypart_id bp, int &damage, int &pain)
 
void longpull (const std::string &name, const tripoint &p)
 Attempts to pull the target at point p towards this creature. More...
 
bool dodge_check (float hit_roll, bool force_try=false, float training_level=0.0f)
 If training_level is anything but 0, the check will only train target's skill to that level. More...
 
bool dodge_check (monster *z, float training_level=0.0f)
 
bool dodge_check (monster *z, bodypart_id bp, const damage_instance &dam_inst, float training_level=0.0f)
 
bool stumble_invis (const Creature &player, bool stumblemsg=true)
 
bool attack_air (const tripoint &p)
 
virtual bool is_ranged_attacker () const
 Returns true if this monster has a gun-type attack or the RANGED_ATTACKER flag. More...
 
virtual bool digging () const
 
bool cant_do_underwater (bool msg=true) const
 
virtual bool is_underwater () const
 
bool is_likely_underwater () const
 
bool is_dangerous_fields (const field &fld) const
 Returns true if there is a field in the field set that is dangerous to us. More...
 
bool is_dangerous_field (const field_entry &entry) const
 Returns true if the given field entry is dangerous to us. More...
 
void check_dead_state ()
 This function checks the creatures is_dead_state and (if true) calls die. More...
 
void add_effect (const effect &eff, bool force=false, bool deferred=false)
 
void add_effect (const efftype_id &eff_id, const time_duration &dur, bodypart_id bp, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 
void add_effect (const efftype_id &eff_id, const time_duration &dur, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 
void add_effect (const effect_source &source, const effect &eff, bool force=false, bool deferred=false)
 
void add_effect (const effect_source &source, const efftype_id &eff_id, const time_duration &dur, bodypart_id bp, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 Adds or modifies an effect. More...
 
void add_effect (const effect_source &source, const efftype_id &eff_id, const time_duration &dur, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 
void schedule_effect (const effect &eff, bool force=false, bool deferred=false)
 Schedules a new effect to be applied. More...
 
void schedule_effect (const efftype_id &eff_id, const time_duration &dur, bodypart_id bp, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 
void schedule_effect (const efftype_id &eff_id, const time_duration &dur, bool permanent=false, int intensity=0, bool force=false, bool deferred=false)
 
bool add_env_effect (const efftype_id &eff_id, const bodypart_id &vector, int strength, const time_duration &dur, const bodypart_id &bp, bool permanent=false, int intensity=1, bool force=false)
 Gives chance to save via environmental resist, returns false if resistance was successful. More...
 
bool add_env_effect (const efftype_id &eff_id, const bodypart_id &vector, int strength, const time_duration &dur, bool permanent=false, int intensity=1, bool force=false)
 
bool remove_effect (const efftype_id &eff_id, const bodypart_id &bp)
 Removes a listed effect. More...
 
bool remove_effect (const efftype_id &eff_id)
 
void schedule_effect_removal (const efftype_id &eff_id, const bodypart_id &bp)
 Schedule effect removal. More...
 
void schedule_effect_removal (const efftype_id &eff_id)
 
void clear_effects ()
 Remove all effects. More...
 
bool has_effect (const efftype_id &eff_id, const bodypart_id &bp) const
 Check if creature has the matching effect. More...
 
bool has_effect (const efftype_id &eff_id) const
 
bool has_effect_with_flag (const flag_id &flag, const bodypart_id &bp) const
 Check if creature has any effect with the given flag. More...
 
bool has_effect_with_flag (const flag_id &flag) const
 
std::vector< std::reference_wrapper< const effect > > get_effects_with_flag (const flag_id &flag) const
 
std::vector< std::reference_wrapper< const effect > > get_effects_from_bp (const bodypart_id &bp) const
 
std::vector< std::reference_wrapper< const effect > > get_effects () const
 
const effectget_effect (const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID()) const
 Return the effect that matches the given arguments exactly. More...
 
effectget_effect (const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID())
 
time_duration get_effect_dur (const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID()) const
 Returns the duration of the matching effect. More...
 
int get_effect_int (const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID()) const
 Returns the intensity of the matching effect. More...
 
bool resists_effect (const effect &e) const
 Returns true if the creature resists an effect. More...
 
void set_value (const std::string &key, const std::string &value)
 
void remove_value (const std::string &key)
 
std::string get_value (const std::string &key) const
 
std::optional< std::string > maybe_get_value (const std::string &key) const
 
void clear_values ()
 
virtual void mod_pain_noresist (int npain)
 
virtual int get_pain () const
 
int get_moves () const
 
void mod_moves (int nmoves)
 
void set_moves (int nmoves)
 
virtual Creatureget_killer () const
 
virtual int get_num_blocks () const
 
virtual int get_num_dodges () const
 
virtual int get_num_blocks_bonus () const
 
virtual int get_num_dodges_bonus () const
 
virtual int get_num_dodges_base () const
 
virtual int get_num_blocks_base () const
 
virtual int get_armor_res (const damage_type_id &dt, bodypart_id bp) const
 
virtual int get_armor_res_base (const damage_type_id &dt, bodypart_id bp) const
 
virtual int get_armor_res_bonus (const damage_type_id &dt) const
 
virtual float get_hit () const
 
virtual int get_hp (const bodypart_id &bp) const
 
virtual int get_hp () const
 
virtual int get_hp_max (const bodypart_id &bp) const
 
virtual int get_hp_max () const
 
virtual bool has_flag (const mon_flag_id &) const
 
void set_reachable_zone (int zone)
 
int get_reachable_zone () const
 
anatomy_id get_anatomy () const
 
void set_anatomy (const anatomy_id &anat)
 
bodypart_id get_random_body_part (bool main=false) const
 
std::vector< bodypart_idget_all_body_parts (get_body_part_flags=get_body_part_flags::none) const
 Returns body parts this creature have. More...
 
std::vector< bodypart_idget_all_body_parts_of_type (body_part_type::type part_type, get_body_part_flags flags=get_body_part_flags::none) const
 
bodypart_id get_random_body_part_of_type (body_part_type::type part_type) const
 
bodypart_id get_root_body_part () const
 
std::vector< bodypart_idget_all_body_parts_with_flag (const json_character_flag &flag) const
 
body_part_set get_drenching_body_parts (bool upper=true, bool mid=true, bool lower=true) const
 
int get_num_body_parts_of_type (body_part_type::type part_type) const
 
int get_num_broken_body_parts_of_type (body_part_type::type part_type) const
 
const std::map< bodypart_str_id, bodypart > & get_body () const
 
void set_body ()
 
bool has_part (const bodypart_id &id, body_part_filter filter=body_part_filter::strict) const
 
bodypartget_part (const bodypart_id &id)
 
const bodypartget_part (const bodypart_id &id) const
 
bodypart_id get_part_id (const bodypart_id &id, body_part_filter filter=body_part_filter::next_best, bool suppress_debugmsg=false) const
 
int get_part_hp_cur (const bodypart_id &id) const
 
int get_part_hp_max (const bodypart_id &id) const
 
int get_part_healed_total (const bodypart_id &id) const
 
int get_part_damage_disinfected (const bodypart_id &id) const
 
int get_part_damage_bandaged (const bodypart_id &id) const
 
int get_part_drench_capacity (const bodypart_id &id) const
 
int get_part_wetness (const bodypart_id &id) const
 
units::temperature get_part_temp_cur (const bodypart_id &id) const
 
units::temperature get_part_temp_conv (const bodypart_id &id) const
 
int get_part_frostbite_timer (const bodypart_id &id) const
 
std::array< int, NUM_WATER_TOLERANCEget_part_mut_drench (const bodypart_id &id) const
 
float get_part_wetness_percentage (const bodypart_id &id) const
 
const encumbrance_dataget_part_encumbrance_data (const bodypart_id &id) const
 
void set_part_hp_max (const bodypart_id &id, int set)
 
void set_part_healed_total (const bodypart_id &id, int set)
 
void set_part_damage_disinfected (const bodypart_id &id, int set)
 
void set_part_damage_bandaged (const bodypart_id &id, int set)
 
void set_part_encumbrance_data (const bodypart_id &id, const encumbrance_data &set)
 
void set_part_wetness (const bodypart_id &id, int set)
 
void set_part_temp_cur (const bodypart_id &id, units::temperature set)
 
void set_part_temp_conv (const bodypart_id &id, units::temperature set)
 
void set_part_frostbite_timer (const bodypart_id &id, int set)
 
void set_part_mut_drench (const bodypart_id &id, std::pair< water_tolerance, int > set)
 
void mod_part_hp_max (const bodypart_id &id, int mod)
 
void mod_part_healed_total (const bodypart_id &id, int mod)
 
void mod_part_damage_disinfected (const bodypart_id &id, int mod)
 
void mod_part_damage_bandaged (const bodypart_id &id, int mod)
 
void mod_part_wetness (const bodypart_id &id, int mod)
 
void mod_part_temp_cur (const bodypart_id &id, units::temperature_delta mod)
 
void mod_part_temp_conv (const bodypart_id &id, units::temperature_delta mod)
 
void mod_part_frostbite_timer (const bodypart_id &id, int mod)
 
void set_all_parts_temp_cur (units::temperature set)
 
void set_all_parts_temp_conv (units::temperature set)
 
void set_all_parts_wetness (int set)
 
void set_all_parts_hp_cur (int set)
 
void set_all_parts_hp_to_max ()
 
bool has_atleast_one_wet_part () const
 
bool is_part_at_max_hp (const bodypart_id &id) const
 
virtual int get_speed_base () const
 
virtual int get_speed_bonus () const
 
virtual int get_block_bonus () const
 
virtual int get_bash_bonus () const
 
virtual int get_cut_bonus () const
 
virtual float get_dodge_bonus () const
 
virtual float get_hit_bonus () const
 
virtual float get_bash_mult () const
 
virtual float get_cut_mult () const
 
virtual bool get_melee_quiet () const
 
virtual int get_throw_resist () const
 
virtual void set_num_blocks_bonus (int nblocks)
 
virtual void mod_num_blocks_bonus (int nblocks)
 
virtual void mod_num_dodges_bonus (int ndodges)
 
virtual void set_armor_res_bonus (int narm, const damage_type_id &dt)
 
virtual void set_speed_base (int nspeed)
 
virtual void set_speed_bonus (int nspeed)
 
virtual void set_block_bonus (int nblock)
 
virtual void set_bash_bonus (int nbash)
 
virtual void set_cut_bonus (int ncut)
 
virtual void mod_speed_bonus (int nspeed)
 
virtual void mod_block_bonus (int nblock)
 
virtual void mod_bash_bonus (int nbash)
 
virtual void mod_cut_bonus (int ncut)
 
virtual void mod_size_bonus (int nsize)
 
virtual void set_dodge_bonus (float ndodge)
 
virtual void set_hit_bonus (float nhit)
 
virtual void mod_dodge_bonus (float ndodge)
 
virtual void mod_hit_bonus (float nhit)
 
virtual void set_bash_mult (float nbashmult)
 
virtual void set_cut_mult (float ncutmult)
 
virtual void set_melee_quiet (bool nquiet)
 
virtual void set_throw_resist (int nthrowres)
 
void draw (const catacurses::window &w, const point &origin, bool inverted) const
 
void draw (const catacurses::window &w, const tripoint &origin, bool inverted) const
 
void describe_infrared (std::vector< std::string > &buf) const
 Describe this creature as seen by the avatar via infrared vision. More...
 
void describe_specials (std::vector< std::string > &buf) const
 Describe this creature as detected by the avatar's special senses. More...
 
void add_msg_if_player (const translation &) const
 
void add_msg_if_player (const game_message_params &, const translation &) const
 
template<typename ... Args>
void add_msg_if_player (const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const translation &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_player (const game_message_params &params, const translation &msg, Args &&... args) const
 
void add_msg_if_npc (const translation &) const
 
void add_msg_if_npc (const game_message_params &, const translation &) const
 
template<typename ... Args>
void add_msg_if_npc (const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_npc (const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_npc (const translation &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_npc (const game_message_params &params, const char *const msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_npc (const game_message_params &params, const std::string &msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_if_npc (const game_message_params &params, const translation &msg, Args &&... args) const
 
void add_msg_player_or_npc (const translation &, const translation &) const
 
void add_msg_player_or_npc (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_npc (const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const char *const player_msg, const char *const npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const std::string &player_msg, const std::string &npc_msg, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_npc (const game_message_params &params, const translation &player_msg, const translation &npc_msg, Args &&... args) const
 
void add_msg_player_or_say (const translation &, const translation &) const
 
void add_msg_player_or_say (const game_message_params &, const translation &, const translation &) const
 
template<typename ... Args>
void add_msg_player_or_say (const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const char *const player_msg, const char *const npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const std::string &player_msg, const std::string &npc_speech, Args &&... args) const
 
template<typename ... Args>
void add_msg_player_or_say (const game_message_params &params, const translation &player_msg, const translation &npc_speech, Args &&... args) const
 
virtual bool is_symbol_highlighted () const
 
std::unordered_map< std::string, std::string > & get_values ()
 
void clear_killer ()
 
void set_summon_time (const time_duration &length)
 
void decrement_summon_timer ()
 
void set_summoner (Creature *summoner)
 
void set_summoner (character_id summoner)
 
Creatureget_summoner () const
 
bodypart_id get_max_hitsize_bodypart () const
 
bodypart_id select_body_part (int min_hit, int max_hit, bool can_attack_high, int hit_roll) const
 
bodypart_id select_blocking_part (bool arm, bool leg, bool nonstandard) const
 
bodypart_id random_body_part (bool main_parts_only=false) const
 
std::vector< bodypart_idget_all_eligable_parts (int min_hit, int max_hit, bool can_attack_high) const
 
void add_damage_over_time (const damage_over_time_data &DoT)
 
void process_damage_over_time ()
 
std::string replace_with_npc_name (std::string input) const
 This function replaces the "<npcname>" substring with the disp_name of this creature. More...
 
tripoint_abs_ms get_location () const
 Returns the location of the creature in map square coordinates (the most detailed coordinate system), relative to a fixed global point of origin. More...
 
tripoint_abs_sm global_sm_location () const
 Returns the location of the creature in global submap coordinates. More...
 
tripoint_abs_omt global_omt_location () const
 Returns the location of the creature in global overmap terrain coordinates. More...
 
- Public Member Functions inherited from viewer
virtual ~viewer ()=default
 
- Public Member Functions inherited from visitable
item remove_item (item &it)
 Removes and returns the item which must be contained by this instance. More...
 
- Public Member Functions inherited from read_only_visitable
itemfind_parent (const item &it) const
 Determine the immediate parent container (if any) for an item. More...
 
std::vector< item * > parents (const item &it) const
 Returns vector of parent containers (if any) starting with the innermost. More...
 
bool has_item (const item &it) const
 Returns true if this visitable instance contains the item. More...
 
bool has_item_with (const std::function< bool(const item &)> &filter) const
 Returns true if any item (including those within a container) matches the filter. More...
 
std::pair< int, int > kcal_range (const itype_id &id, const std::function< bool(const item &)> &filter, Character &player_character) const
 
bool has_amount (const itype_id &what, int qty, bool pseudo=true, const std::function< bool(const item &)> &filter=return_true< item >) const
 Check instance provides at least qty of an item (. More...
 
std::vector< item * > items_with (const std::function< bool(const item &)> &filter)
 Returns all items (including those within a container) matching the filter. More...
 
std::vector< const item * > items_with (const std::function< bool(const item &)> &filter) const
 
virtual ~read_only_visitable ()=default
 
bool has_tools (const itype_id &it, int quantity, const std::function< bool(const item &)> &filter=return_true< item >) const
 
bool has_components (const itype_id &it, int quantity, const std::function< bool(const item &)> &filter=return_true< item >) const
 

Static Public Member Functions

static std::string get_need_str_id (const npc_need &need)
 
static overmap_location_str_id get_location_for (const npc_need &need)
 
static bool theft_witness_compare (const npc *lhs, const npc *rhs)
 
- Static Public Member Functions inherited from Character
static int thirst_speed_penalty (int thirst)
 Returns the penalty to speed from thirst. More...
 
static int worn_position_to_index (int position)
 
static units::temperature_delta floor_bedding_warmth (const tripoint &pos)
 Warmth from terrain, furniture, vehicle furniture and traps. More...
 
static units::temperature_delta floor_item_warmth (const tripoint &pos)
 Warmth from clothing on the floor. More...
 
static int min_height (creature_size size_category=creature_size::medium)
 Min, max and default heights for each size category of a character in centimeters. More...
 
static int default_height (creature_size size_category=creature_size::medium)
 
static int max_height (creature_size size_category=creature_size::medium)
 
- Static Public Member Functions inherited from Creature
static std::string attitude_raw_string (Attitude att)
 Simplified attitude string for unlocalized needs. More...
 
static const std::pair< translation, nc_color > & get_attitude_ui_data (Attitude att)
 Creature Attitude as String and color. More...
 
static void load_hit_range (const JsonObject &)
 

Public Attributes

weak_ptr_fast< monsterchosen_mount
 
activity_id current_activity_id = activity_id::NULL_ID()
 
npc_class_id myclass
 
string_id< npc_templateidz
 
std::vector< mission_type_idmiss_ids
 
std::optional< tripoint_abs_omtassigned_camp = std::nullopt
 
std::optional< tripoint_abs_mslast_player_seen_pos
 
std::optional< tripoint_abs_msgoto_to_this_pos
 
int last_seen_player_turn = 0
 
item_location wanted_item = {}
 
tripoint wanted_item_pos
 
std::optional< tripoint_abs_msguard_pos
 
std::optional< tripoint_abs_mschair_pos
 
std::optional< tripoint_abs_omtbase_location
 
tripoint_abs_omt goal
 Global overmap terrain coordinate, where we want to get to if no goal exist, this is no_goal_point. More...
 
std::optional< tripoint_abs_mswander_pos
 
itemknown_stolen_item = nullptr
 
std::optional< tripoint_abs_mspulp_location
 
time_point restock
 
bool fetching_item = false
 
bool has_new_items = false
 
int worst_item_value = 0
 
std::vector< tripointpath
 
std::string companion_mission_role_id
 
std::vector< tripoint_abs_omtcompanion_mission_points
 
time_point companion_mission_time
 
time_point companion_mission_time_ret
 
inventory companion_mission_inv
 
npc_mission mission = NPC_MISSION_NULL
 
npc_mission previous_mission = NPC_MISSION_NULL
 
npc_personality personality
 
npc_opinion op_of_u
 
npc_combat_memory_cache mem_combat
 
dialogue_chatbin chatbin
 
int patience = 0
 
npc_follower_rules rules
 
bool marked_for_death = false
 
bool hit_by_player = false
 
bool hallucination = false
 
std::vector< npc_needneeds
 
std::optional< int > confident_range_cache
 
job_data job
 
- Public Attributes inherited from Character
bool death_drops
 Turned to false for simulating NPCs on distant missions so they don't drop all their gear in sight. More...
 
bool controlling_vehicle = false
 Is currently in control of a vehicle. More...
 
int str_max
 Character stats. More...
 
int dex_max
 
int int_max
 
int per_max
 
int str_cur
 
int dex_cur
 
int int_cur
 
int per_cur
 
int kill_xp = 0
 
int spent_upgrade_points = 0
 
float cached_organic_size
 
const professionprof
 
std::set< const profession * > hobbies
 
tripoint grab_point
 
std::optional< citystarting_city
 
std::optional< point_abs_omworld_origin
 
bool random_start_location = true
 
start_location_id start_location
 
bool manual_examine = false
 
int volume = 0
 
int arms_power_use
 Cache variables to store stamina use info these will be updated when the player's limb makeup changes _power_use is how many joules to spend per stamina instead of stamina (default 0) _stam_mult is how much to multiply the incoming stamina cost's stamina drain (default of 1) More...
 
int legs_power_use
 
float arms_stam_mult
 
float legs_stam_mult
 
int blocks_left
 
double recoil = MAX_RECOIL
 
std::string custom_profession
 
bool reach_attacking = false
 
std::vector< tripoint_abs_omtomt_path
 
std::unordered_set< tripoint_abs_omtmap_revealed_omts
 
pimpl< known_magicmagic
 
std::string name
 
std::optional< std::string > play_name
 
bool male = false
 
std::vector< effect_on_condition_iddeath_eocs
 
outfit worn
 
bool nv_cached = false
 
bool in_vehicle = false
 
bool hauling = false
 
bool autohaul = false
 
bool suppress_autohaul = false
 
std::string hauling_filter
 
std::vector< item_locationhaul_list
 
tripoint view_offset
 
player_activity stashed_outbounds_activity
 
player_activity stashed_outbounds_backlog
 
player_activity activity
 
std::list< player_activitybacklog
 
std::optional< tripointdestination_point
 
pimpl< inventoryinv
 
itype_id last_item
 
int scent = 0
 
pimpl< bionic_collectionmy_bionics
 
pimpl< character_martial_artsmartial_arts_data
 
stomach_contents stomach
 
stomach_contents guts
 
std::list< consumption_eventconsumption_history
 
int oxygen = 0
 
int slow_rad = 0
 
blood_type my_blood_type
 
bool blood_rh_factor = false
 
int avg_nat_bpm
 
int cash = 0
 
weak_ptr_fast< Creaturelast_target
 
std::optional< tripointlast_target_pos
 
item_location ammo_location
 
std::set< tripoint_abs_omtcamps
 
std::vector< addictionaddictions
 
std::vector< effect_on_condition_idinactive_effect_on_condition_vector
 
queued_eocs queued_effect_on_conditions
 
shared_ptr_fast< monstermounted_creature
 
int mounted_creature_id = 0
 
int activity_vehicle_part_index = -1
 
std::map< mutation_category_id, int > mutation_category_level
 
moncam_cache_t moncam_cache
 
pimpl< craft_commandlast_craft
 
recipe_id lastrecipe
 
int last_batch
 
int str_bonus = 0
 Bonuses to stats, calculated each turn. More...
 
int dex_bonus = 0
 
int per_bonus = 0
 
int int_bonus = 0
 
int str_bonus_hardcoded = 0
 Hardcoded stats bonus. More...
 
int dex_bonus_hardcoded = 0
 
int per_bonus_hardcoded = 0
 
int int_bonus_hardcoded = 0
 
int enchantment_speed_bonus = 0
 
int lifestyle = 0
 How healthy the character is. More...
 
int daily_health = 0
 
int health_tally = 0
 
int init_age = 25
 age in years at character creation More...
 
int init_height = 175
 height at character creation More...
 
creature_size size_class = creature_size::medium
 Size class of character. More...
 
activity_tracker activity_history
 
int old_weary_level = 0
 
trap_map known_traps
 
std::map< std::string, double > cached_info
 
bool bio_soporific_powered_at_last_sleep_check = false
 
time_point last_sleep_check = calendar::turn_zero
 last time we checked for sleep More...
 
std::map< faction_id, std::pair< int, time_point > > warning_record
 warnings from a faction about bad behavior More...
 
std::unordered_map< trait_id, trait_datamy_mutations
 Traits / mutations of the character. More...
 
std::unordered_set< trait_idmy_traits
 Contains mutation ids of the base traits. More...
 
std::vector< const mutation_branch * > cached_mutations
 Pointers to mutation branches in my_mutations. More...
 
std::vector< trait_idmutations_to_remove
 
std::vector< trait_idmutations_to_add
 
std::optional< units::masscached_weight_carried = std::nullopt
 The amount of weight the Character is carrying. More...
 
pimpl< SkillLevelMap_skills
 
pimpl< proficiency_set_proficiencies
 
std::bitset< NUM_VISION_MODESvision_mode_cache
 
int sight_max = 0
 
time_point time_died = calendar::before_time_starts
 turn the character expired, if calendar::before_time_starts it has not been set yet. More...
 
pimpl< pathfinding_settingspath_settings
 Cache for pathfinding settings. More...
 
int faction_api_version = 2
 
faction_id fac_id
 
factionmy_fac = nullptr
 
move_mode_id move_mode
 
std::map< vitamin_id, int > vitamin_levels
 Current deficiency/excess quantity for each vitamin. More...
 
std::map< vitamin_id, std::pair< int, int > > daily_vitamins
 Current quantity for each vitamin today first value is expected second value is actual (digested) in vitamin units. More...
 
pimpl< player_moralemorale
 
time_point next_climate_control_check
 
bool last_climate_control_ret
 
pimpl< enchant_cacheenchantment_cache
 
- Public Attributes inherited from Creature
FacingDirection facing = FacingDirection::RIGHT
 return the direction the creature is facing, for sdl horizontal flip More...
 
bool underwater
 
int archery_aim_counter = 0
 

Static Public Attributes

static std::array< std::pair< std::string, overmap_location_str_id >, npc_need::num_needsneed_data
 
static constexpr tripoint_abs_omt no_goal_point { tripoint_min }
 
- Static Public Attributes inherited from Character
static const std::vector< material_idfleshy = { material_flesh, material_hflesh }
 
- Static Public Attributes inherited from Creature
static const std::map< std::string, creature_sizesize_map
 
static const std::set< material_idcmat_flesh
 
static const std::set< material_idcmat_fleshnveg
 
static const std::set< material_idcmat_flammable
 
static const std::set< material_idcmat_flameres
 
static std::vector< int > dispersion_for_even_chance_of_good_hit
 

Protected Member Functions

void store (JsonOut &json) const
 
void load (const JsonObject &data)
 
void on_move (const tripoint_abs_ms &old_pos) override
 
- Protected Member Functions inherited from Character
void mod_stored_calories (int ncal, bool ignore_weariness=false)
 
void set_stored_calories (int cal)
 
float generic_weakpoint_skill (skill_id skill_1, skill_id skill_2, limb_score_id limb_score_1, limb_score_id limb_score_2) const
 
void set_mutation_unsafe (const trait_id &, const mutation_variant *=nullptr)
 
void do_skill_rust ()
 
void apply_mods (const trait_id &mut, bool add_remove)
 Applies stat mods to character. More...
 
void mut_cbm_encumb (std::map< bodypart_id, encumbrance_data > &vals) const
 Applies encumbrance from mutations and bionics only. More...
 
void apply_mut_encumbrance (std::map< bodypart_id, encumbrance_data > &vals) const
 
void calc_bmi_encumb (std::map< bodypart_id, encumbrance_data > &vals) const
 Applies encumbrance from BMI. More...
 
void calc_bmi_encumb () const
 
void on_damage_of_type (const effect_source &source, int adjusted_damage, const damage_type_id &dt, const bodypart_id &bp) override
 
recipe_subset get_available_recipes (const inventory &crafting_inv, const std::vector< Character * > *helpers=nullptr) const
 Return all available recipes (from books and companions) More...
 
 Character ()
 
 Character (Character &&) noexcept(map_is_noexcept)
 
Characteroperator= (Character &&) noexcept(list_is_noexcept)
 
void swap_character (Character &other)
 
- Protected Member Functions inherited from Creature
void set_pos_only (const tripoint &p)
 
void set_location (const tripoint_abs_ms &loc)
 
void set_killer (Creature *killer)
 
 Creature ()
 
 Creature (const Creature &)
 
 Creature (Creature &&) noexcept(map_is_noexcept)
 
Creatureoperator= (const Creature &)
 
Creatureoperator= (Creature &&) noexcept
 
void store (JsonOut &jsout) const
 These two functions are responsible for storing and loading the members of this class to/from json data. More...
 
void load (const JsonObject &jsin)
 

Private Member Functions

void import_and_clean (const JsonObject &data)
 
bool sees_dangerous_field (const tripoint &p) const
 
bool could_move_onto (const tripoint &p) const
 
bool could_move_onto (const tripoint_bub_ms &p) const
 
std::vector< spherefind_dangerous_explosives () const
 

Private Attributes

npc_attitude attitude = NPCATT_NULL
 
npc_attitude previous_attitude = NPCATT_NULL
 
bool known_to_u = false
 
std::map< std::string, time_pointcomplaints
 
npc_short_term_cache ai_cache
 
std::map< npc_need, npc_need_goal_cachegoal_cache
 
item real_weapon
 
int cbm_weapon_index = -1
 
bool dead = false
 
bool prevent_death_reminder = false
 
npc_companion_mission comp_mission
 
std::string unique_id
 

Additional Inherited Members

- Public Types inherited from Character
enum class  comfort_level : int {
  impossible = -999 , uncomfortable = -7 , neutral = 0 , slightly_comfortable = 3 ,
  comfortable = 5 , very_comfortable = 10
}
 
using cached_moncam = std::pair< monster const *, tripoint_abs_ms >
 
using moncam_cache_t = cata::flat_set< cached_moncam >
 
using trap_map = std::map< tripoint, std::string >
 
- Public Types inherited from Creature
enum class  Attitude : int { HOSTILE , NEUTRAL , FRIENDLY , ANY }
 Simplified attitude towards any creature: hostile - hate, want to kill, etc. More...
 
- Protected Attributes inherited from Character
int focus_pool = 0
 
std::set< mtype_idknown_monsters
 
bionic_uid weapon_bionic_uid = 0
 
bionic_uid next_bionic_uid = 0
 
pimpl< recipe_subsetlearned_recipes
 Subset of learned recipes. More...
 
decltype(_skillsvalid_autolearn_skills
 Stamp of skills. More...
 
std::unordered_map< point_abs_omt, time_durationovermap_time
 Amount of time the player has spent in each overmap tile. More...
 
- Protected Attributes inherited from Creature
anatomy_id creature_anatomy = anatomy_id( "default_anatomy" )
 anatomy is the plan of the creature's body More...
 
std::map< bodypart_str_id, bodypartbody
 this is the actual body of the creature More...
 
int moves
 
Creaturekiller
 
std::optional< time_pointlifespan_end = std::nullopt
 
std::optional< character_idsummoner = std::nullopt
 
pimpl< effects_mapeffects
 
std::queue< scheduled_effect, std::list< scheduled_effect > > scheduled_effects
 
std::queue< terminating_effect, std::list< terminating_effect > > terminating_effects
 
std::vector< damage_over_time_datadamage_over_time_map
 
std::unordered_map< std::string, std::string > values
 
int num_blocks = 0
 
int num_dodges = 0
 
int num_blocks_bonus = 0
 
int num_dodges_bonus = 0
 
std::map< damage_type_id, float > armor_bonus
 
int speed_base = 0
 
int speed_bonus = 0
 
float dodge_bonus = 0.0f
 
int block_bonus = 0
 
float hit_bonus = 0.0f
 
int bash_bonus = 0
 
int cut_bonus = 0
 
int size_bonus = 0
 
float bash_mult = 0.0f
 
float cut_mult = 0.0f
 
bool melee_quiet = false
 
int throw_resist = 0
 
time_point last_updated
 
bool fake = false
 

Detailed Description

Definition at line 791 of file npc.h.

Constructor & Destructor Documentation

◆ npc() [1/3]

npc::npc ( )

Definition at line 218 of file npc.cpp.

222 {
224  last_player_seen_pos = std::nullopt;
225  last_seen_player_turn = 999;
227  guard_pos = std::nullopt;
229  fetching_item = false;
230  has_new_items = true;
231  worst_item_value = 0;
232  str_max = 0;
233  dex_max = 0;
234  int_max = 0;
235  per_max = 0;
236  marked_for_death = false;
237  death_drops = true;
238  dead = false;
239  hit_by_player = false;
240  hallucination = false;
241  moves = 100;
246  patience = 0;
248 
249  *path_settings = pathfinding_settings( 0, 1000, 1000, 10, true, true, true, true, false, true );
250  for( direction threat_dir : npc_threat_dir ) {
251  ai_cache.threat_map[ threat_dir ] = 0.0f;
252  }
253 }
int str_max
Character stats.
Definition: character.h:572
faction_id fac_id
Definition: character.h:3958
int per_max
Definition: character.h:575
bool death_drops
Turned to false for simulating NPCs on distant missions so they don't drop all their gear in sight.
Definition: character.h:557
pimpl< pathfinding_settings > path_settings
Cache for pathfinding settings.
Definition: character.h:3950
int int_max
Definition: character.h:574
int dex_max
Definition: character.h:573
int moves
Definition: creature.h:1193
time_point last_updated
Definition: creature.h:1238
npc_short_term_cache ai_cache
Definition: npc.h:1348
int worst_item_value
Definition: npc.h:1388
int patience
Definition: npc.h:1407
tripoint wanted_item_pos
Definition: npc.h:1369
bool fetching_item
Definition: npc.h:1386
npc_class_id myclass
Definition: npc.h:1329
time_point restock
Definition: npc.h:1385
tripoint_abs_omt goal
Global overmap terrain coordinate, where we want to get to if no goal exist, this is no_goal_point.
Definition: npc.h:1379
bool marked_for_death
Definition: npc.h:1409
npc_attitude attitude
Definition: npc.h:1342
int last_seen_player_turn
Definition: npc.h:1364
bool dead
Definition: npc.h:1464
bool has_new_items
Definition: npc.h:1387
std::optional< tripoint_abs_ms > guard_pos
Definition: npc.h:1371
time_point companion_mission_time_ret
Definition: npc.h:1398
std::optional< tripoint_abs_ms > last_player_seen_pos
Definition: npc.h:1361
bool hit_by_player
Definition: npc.h:1410
string_id< npc_template > idz
Definition: npc.h:1330
time_point companion_mission_time
Definition: npc.h:1396
bool hallucination
Definition: npc.h:1411
static const string_id< npc_class > & NULL_ID()
Returns a null id whose string_id<T>::is_null() must always return true.
coords::coord_point< tripoint, coords::origin::abs, coords::omt > tripoint_abs_omt
Definition: coordinates.h:726
direction
Definition: line.h:42
constexpr time_point turn_zero
Represents time point 0.
Definition: calendar.h:541
constexpr time_point before_time_starts
A time point that is always before the current turn, even when the game has just started.
Definition: calendar.h:535
time_point turn
Definition: calendar.cpp:38
@ NPCATT_NULL
Definition: npc.h:107
@ NPC_MISSION_NULL
Definition: npc.h:172
constexpr std::array< direction, 8 > npc_threat_dir
Definition: npc.h:544
constexpr tripoint tripoint_min
Definition: point.h:293
std::map< direction, float > threat_map
Definition: npc.h:591

References ai_cache, attitude, dead, Character::death_drops, Character::dex_max, Character::fac_id, fetching_item, goal, guard_pos, hallucination, has_new_items, hit_by_player, idz, Character::int_max, last_player_seen_pos, last_seen_player_turn, Creature::last_updated, marked_for_death, Creature::moves, myclass, NPC_MISSION_NULL, npc_threat_dir, NPCATT_NULL, string_id< T >::NULL_ID(), string_id< faction >::NULL_ID(), string_id< npc_class >::NULL_ID(), Character::path_settings, patience, Character::per_max, Character::str_max, npc_short_term_cache::threat_map, tripoint_min, calendar::turn, wanted_item_pos, and worst_item_value.

◆ npc() [2/3]

npc::npc ( const npc )
delete

◆ npc() [3/3]

npc::npc ( npc &&  )
defaultnoexcept

◆ ~npc()

npc::~npc ( )
overridedefault

Member Function Documentation

◆ act_on_danger_assessment()

void npc::act_on_danger_assessment ( )

Definition at line 1101 of file npcmove.cpp.

1102 {
1103  bool npc_ranged = get_wielded_item() && get_wielded_item()->is_gun();
1104  bool failed_reposition = false;
1105  Character &player_character = get_player_character();
1106  if( has_effect( effect_npc_run_away ) ) {
1107  // this check runs each turn that the NPC is repositioning and assesses if the situation is getting any better.
1108  // The longer they try to move without improving, the more likely they become to stop and stand their ground.
1109  const bool melee_reposition_fail = !npc_ranged &&
1111  const bool range_reposition_fail = npc_ranged &&
1114  if( melee_reposition_fail || range_reposition_fail ) {
1116  "<color_light_red>%s tried to reposition last turn, and the situation has not improved.</color>",
1117  name );
1118  failed_reposition = true;
1120  } else {
1122  "<color_light_green>%s tried to reposition last turn, and it worked out!</color>",
1123  name );
1125  }
1126  }
1130  // Each time NPC decides to run away, their panic increases, which increases likelihood
1131  // and duration of running away.
1132  // if they run to a more advantageous position, they'll reassess and rally.
1133  time_duration run_away_for = std::max( 2_turns + 1_turns * mem_combat.panic, 20_turns );
1134 
1135  if( mem_combat.reposition_countdown <= 0 ) {
1137  "%s decides to reposition. Has not yet decided to flee.", name );
1138  mem_combat.repositioning = true;
1139  add_effect( effect_npc_run_away, run_away_for );
1140  path.clear();
1141  } else {
1142  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s still wants to reposition, but they just tried.",
1143  name );
1144  }
1147  rng( 1, 3 ) + ( get_pain() / 5 ) - personality.bravery, 1 );
1148 
1150  // NPC hasn't yet failed to get away
1151  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s upgrades reposition to flat out retreat.", name );
1152  mem_combat.repositioning = false; // we're not just moving, we're running.
1153  warn_about( "run_away", run_away_for );
1154  if( mem_combat.panic > 5 && is_player_ally() && sees( player_character.pos() ) ) {
1155  // consider warning player about panic
1156  int panic_alert = rl_dist( pos(), player_character.pos() ) - player_character.get_per();
1157  if( mem_combat.panic - personality.bravery > panic_alert ) {
1158  if( one_in( 4 ) && mem_combat.panic < 10 + personality.bravery ) {
1159  add_msg( m_bad, _( "%s is starting to panic a bit." ), name );
1160  } else if( mem_combat.panic >= 10 + personality.bravery ) {
1161  add_msg( m_bad, _( "%s is panicking!" ), name );
1162  }
1163  }
1164  }
1165  }
1166  } else if( failed_reposition ||
1169  "<color_light_gray>%s considers </color>repositioning<color_light_gray> from swarming enemies.</color>",
1170  name );
1171  if( failed_reposition ) {
1172  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s failed repositioning, trying again.", name );
1174  } else {
1176  "%s decided to reposition/kite due to %i nearby enemies.",
1178  }
1179  mem_combat.repositioning = true;
1180  // you chose not to run, but there are enough of them coming in that you should probably back away a bit.
1181 
1182  time_duration run_away_for = 2_turns;
1183  add_effect( effect_npc_run_away, run_away_for );
1184  path.clear();
1185  } else {
1186  // Things seem to be going okay, reset/reduce "worry" memories.
1187  if( mem_combat.panic > 0 ) {
1188  mem_combat.panic -= 1;
1189  }
1191  }
1192  }
1194  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s <color_magenta>panic level</color> is up to %i.",
1195  name, mem_combat.panic );
1198  // NPC is fleeing, but hasn't been able to reposition safely.
1199  // Consider cancelling fleeing.
1200  // Note that panic will still increment prior to this, and a truly panicked NPC will not stand and fight for any reason.
1202  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s decided running away was futile.", name );
1205  path.clear();
1206  }
1207  }
1208 }
time_duration rng(time_duration lo, time_duration hi)
Definition: calendar.cpp:779
Character & get_player_character()
Definition: game.cpp:13807
std::string name
Definition: character.h:2684
bool sees(const tripoint &t, bool is_avatar=false, int range_mod=0) const override
item_location get_wielded_item() const
Definition: character.cpp:674
int get_per() const
Definition: character.cpp:4135
tripoint pos() const
Definition: creature.cpp:178
bool remove_effect(const efftype_id &eff_id, const bodypart_id &bp)
Removes a listed effect.
Definition: creature.cpp:1722
void add_effect(const effect &eff, bool force=false, bool deferred=false)
Definition: creature.h:604
virtual int get_pain() const
Definition: creature.cpp:1994
bool has_effect(const efftype_id &eff_id, const bodypart_id &bp) const
Check if creature has the matching effect.
Definition: creature.cpp:1770
bool is_gun() const
Can this item be used to perform a ranged attack?
Definition: item.cpp:9297
std::vector< tripoint > path
Definition: npc.h:1390
void warn_about(const std::string &type, const time_duration &d=10_minutes, const std::string &name="", int range=-1, const tripoint &danger_pos=tripoint_zero)
Definition: npcmove.cpp:5153
npc_personality personality
Definition: npc.h:1402
npc_combat_memory_cache mem_combat
Definition: npc.h:1404
bool is_player_ally() const
Definition: npc.cpp:2297
A duration defined as a number of specific time units.
Definition: calendar.h:197
int rl_dist(const coords::coord_point< Point, Origin, Scale, LhsInBounds > &loc1, const coords::coord_point< Point, Origin, Scale, RhsInBounds > &loc2)
Definition: coordinates.h:769
@ m_bad
Definition: enums.h:348
double round(std::vector< double > const &params)
double max(std::vector< double > const &params)
double min(std::vector< double > const &params)
void add_msg(std::string msg)
Definition: messages.cpp:997
#define add_msg_debug(type,...)
Definition: messages.h:177
@ DF_NPC_COMBATAI
Definition: debug.h:268
static const efftype_id effect_npc_fire_bad("npc_fire_bad")
static const efftype_id effect_npc_run_away("npc_run_away")
bool one_in(int chance)
Definition: rng.cpp:108
int assessment_before_repos
Definition: npc.h:609
int failing_to_reposition
Definition: npc.h:607
int reposition_countdown
Definition: npc.h:608
int8_t bravery
Definition: npc.h:218
#define _(STRING)
Definition: translations.h:89

References _, Creature::add_effect(), add_msg(), add_msg_debug, npc_combat_memory_cache::assess_ally, npc_combat_memory_cache::assess_enemy, npc_combat_memory_cache::assessment_before_repos, npc_personality::bravery, debugmode::DF_NPC_COMBATAI, effect_npc_fire_bad, effect_npc_run_away, npc_combat_memory_cache::failing_to_reposition, Creature::get_pain(), Character::get_per(), get_player_character(), Character::get_wielded_item(), Creature::has_effect(), item::is_gun(), is_player_ally(), m_bad, max(), mem_combat, min(), Character::name, one_in(), npc_combat_memory_cache::panic, path, personality, Creature::pos(), Creature::remove_effect(), npc_combat_memory_cache::reposition_countdown, npc_combat_memory_cache::repositioning, rl_dist(), rng(), round(), Character::sees(), npc_combat_memory_cache::swarm_count, and warn_about().

Referenced by move().

◆ activate_bionic_by_id()

bool npc::activate_bionic_by_id ( const bionic_id cbm_id,
bool  eff_only = false 
)

Definition at line 2234 of file npcmove.cpp.

2235 {
2236  for( bionic &i : *my_bionics ) {
2237  if( i.id == cbm_id ) {
2238  if( !i.powered ) {
2239  return activate_bionic( i, eff_only );
2240  } else {
2241  return false;
2242  }
2243  }
2244  }
2245  return false;
2246 }
pimpl< bionic_collection > my_bionics
Definition: character.h:2723
bool activate_bionic(bionic &bio, bool eff_only=false, bool *close_bionics_ui=nullptr)
Handles bionic activation effects of the entered bionic, returns if anything activated.
Definition: bionics.cpp:722

References Character::activate_bionic(), and Character::my_bionics.

Referenced by activate_combat_cbms(), address_needs(), complain(), execute_action(), move_pause(), and npc_attack_melee::use().

◆ activate_combat_cbms()

void npc::activate_combat_cbms ( )

Definition at line 2209 of file npcmove.cpp.

2210 {
2211  for( const bionic_id &cbm_id : defense_cbms ) {
2212  activate_bionic_by_id( cbm_id );
2213  }
2214  if( can_use_offensive_cbm() ) {
2215  for( const bionic_id &cbm_id : weapon_cbms ) {
2216  check_or_use_weapon_cbm( cbm_id );
2217  }
2218  }
2219 }
bool activate_bionic_by_id(const bionic_id &cbm_id, bool eff_only=false)
Definition: npcmove.cpp:2234
bool can_use_offensive_cbm() const
Definition: npcmove.cpp:2293
void check_or_use_weapon_cbm(const bionic_id &cbm_id)
Definition: bionics.cpp:623
const std::vector< bionic_id > defense_cbms
Definition: npcmove.cpp:192
const std::vector< bionic_id > weapon_cbms
Definition: npcmove.cpp:209

References activate_bionic_by_id(), can_use_offensive_cbm(), check_or_use_weapon_cbm(), anonymous_namespace{npcmove.cpp}::defense_cbms, and anonymous_namespace{npcmove.cpp}::weapon_cbms.

Referenced by prepare_for_combat().

◆ activate_combat_items()

void npc::activate_combat_items ( )

Definition at line 2344 of file npcmove.cpp.

2345 {
2346  worn.activate_combat_items( *this );
2347 }
outfit worn
Definition: character.h:2690
void activate_combat_items(npc &guy)
Definition: npcmove.cpp:2321

References outfit::activate_combat_items(), and Character::worn.

Referenced by prepare_for_combat().

◆ activate_item()

void npc::activate_item ( item it)

Definition at line 4314 of file npcmove.cpp.

4315 {
4316  const int oldmoves = moves;
4317  if( it.is_tool() || it.is_food() ) {
4318  it.type->invoke( this, it, pos() );
4319  }
4320 
4321  if( moves == oldmoves ) {
4322  // HACK: A hack to prevent debugmsgs when NPCs activate 0 move items
4323  // while not removing the debugmsgs for other 0 move actions
4324  moves--;
4325  }
4326 }
bool is_tool() const
Definition: item.cpp:9953
bool is_food() const
Definition: item.cpp:9480
const itype * type
Definition: item.h:3074
std::optional< int > invoke(Character *p, item &it, const tripoint &pos) const
Definition: itype.cpp:195

References itype::invoke(), item::is_food(), item::is_tool(), Creature::moves, Creature::pos(), and item::type.

Referenced by alt_attack(), and npc_attack_activate_item::use().

◆ add_msg_if_npc() [1/2]

void npc::add_msg_if_npc ( const game_message_params params,
const std::string &  msg 
) const
overridevirtual

Reimplemented from Creature.

Definition at line 3026 of file npc.cpp.

3027 {
3028  add_msg( params, replace_with_npc_name( msg ) );
3029 }
std::string replace_with_npc_name(std::string input) const
This function replaces the "<npcname>" substring with the disp_name of this creature.
Definition: creature.cpp:3108

References add_msg(), and Creature::replace_with_npc_name().

◆ add_msg_if_npc() [2/2]

void npc::add_msg_if_npc ( const std::string &  msg) const
overridevirtual

Reimplemented from Creature.

Definition at line 3015 of file npc.cpp.

3016 {
3017  add_msg( replace_with_npc_name( msg ) );
3018 }

References add_msg(), and Creature::replace_with_npc_name().

Referenced by outfit::activate_combat_items(), outfit::deactivate_combat_items(), move_to(), set_attitude(), stow_item(), and wield().

◆ add_msg_if_player() [1/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

982  {
983  return add_msg_if_player( string_format( msg, std::forward<Args>( args )... ) );
984  }
void add_msg_if_player(const std::string &msg) const override
Definition: character.cpp:856
std::string string_format(std::string_view format, Args &&...args)
Simple wrapper over string_formatter::parse.

◆ add_msg_if_player() [2/14]

virtual void Creature::add_msg_if_player
inline

Definition at line 753 of file creature.h.

978  {}

◆ add_msg_if_player() [3/14]

void npc::add_msg_if_player ( const game_message_params ,
const std::string &   
) const
inlineoverridevirtual

Reimplemented from Character.

Definition at line 1287 of file npc.h.

1288  {}

◆ add_msg_if_player() [4/14]

void Creature::add_msg_if_player

Definition at line 753 of file creature.cpp.

3146 {
3147  return add_msg_if_player( params, msg.translated() );
3148 }

◆ add_msg_if_player() [5/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

995  {
996  if( params.type == m_debug && !debug_mode ) {
997  return;
998  }
999  return add_msg_if_player( params, string_format( msg, std::forward<Args>( args )... ) );
1000  }
bool debug_mode
Extended debugging mode, can be toggled during game.
Definition: debug.cpp:210
@ m_debug
Definition: enums.h:358

◆ add_msg_if_player() [6/14]

void Character::add_msg_if_player
override

Definition at line 755 of file character.cpp.

868 {
869  Messages::add_msg( params, msg );
870 }
void add_msg(std::string msg)
Definition: messages.cpp:454

◆ add_msg_if_player() [7/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

1003  {
1004  if( params.type == m_debug && !debug_mode ) {
1005  return;
1006  }
1007  return add_msg_if_player( params, string_format( msg, std::forward<Args>( args )... ) );
1008  }

◆ add_msg_if_player() [8/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

1011  {
1012  if( params.type == m_debug && !debug_mode ) {
1013  return;
1014  }
1015  return add_msg_if_player( params, string_format( msg, std::forward<Args>( args )... ) );
1016  }

◆ add_msg_if_player() [9/14]

virtual void Creature::add_msg_if_player
inline

Definition at line 753 of file creature.h.

976 {}

◆ add_msg_if_player() [10/14]

void npc::add_msg_if_player ( const std::string &  ) const
inlineoverridevirtual

Reimplemented from Character.

Definition at line 1286 of file npc.h.

1286 {}

◆ add_msg_if_player() [11/14]

void Character::add_msg_if_player
override

Definition at line 754 of file character.cpp.

857 {
858  Messages::add_msg( msg );
859 }

◆ add_msg_if_player() [12/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

986  {
987  return add_msg_if_player( string_format( msg, std::forward<Args>( args )... ) );
988  }

◆ add_msg_if_player() [13/14]

void Creature::add_msg_if_player

Definition at line 753 of file creature.cpp.

3141 {
3142  return add_msg_if_player( msg.translated() );
3143 }

◆ add_msg_if_player() [14/14]

template<typename ... Args>
void Creature::add_msg_if_player ( typename ...  Args)
inline

Definition at line 753 of file creature.h.

990  {
991  return add_msg_if_player( string_format( msg, std::forward<Args>( args )... ) );
992  }

◆ add_msg_player_or_npc() [1/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1072  {
1073  return add_msg_player_or_npc( string_format( player_msg, std::forward<Args>( args )... ),
1074  string_format( npc_msg, std::forward<Args>( args )... ) );
1075  }
void add_msg_player_or_npc(const std::string &player_msg, const std::string &npc_str) const override
Definition: character.cpp:861

◆ add_msg_player_or_npc() [2/14]

virtual void Creature::add_msg_player_or_npc
inline

Definition at line 756 of file creature.h.

1064  {}

◆ add_msg_player_or_npc() [3/14]

void Creature::add_msg_player_or_npc

Definition at line 756 of file creature.cpp.

3167 {
3168  return add_msg_player_or_npc( params, pc.translated(), npc.translated() );
3169 }
Definition: npc.h:792

◆ add_msg_player_or_npc() [4/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1090  {
1091  if( params.type == m_debug && !debug_mode ) {
1092  return;
1093  }
1094  return add_msg_player_or_npc( params, string_format( player_msg, std::forward<Args>( args )... ),
1095  string_format( npc_msg, std::forward<Args>( args )... ) );
1096  }

◆ add_msg_player_or_npc() [5/14]

void Character::add_msg_player_or_npc
override

Definition at line 759 of file character.cpp.

875 {
876  Messages::add_msg( params, player_msg );
877 }

◆ add_msg_player_or_npc() [6/14]

void npc::add_msg_player_or_npc ( const game_message_params params,
const std::string &  player_msg,
const std::string &  npc_msg 
) const
overridevirtual

Reimplemented from Character.

Definition at line 3031 of file npc.cpp.

3034 {
3035  if( get_player_view().sees( *this ) ) {
3036  add_msg( params, replace_with_npc_name( npc_msg ) );
3037  }
3038 }
viewer & get_player_view()
Definition: game.cpp:13812

References add_msg(), get_player_view(), Creature::replace_with_npc_name(), and Character::sees().

◆ add_msg_player_or_npc() [7/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1099  {
1100  if( params.type == m_debug && !debug_mode ) {
1101  return;
1102  }
1103  return add_msg_player_or_npc( params, string_format( player_msg, std::forward<Args>( args )... ),
1104  string_format( npc_msg, std::forward<Args>( args )... ) );
1105  }

◆ add_msg_player_or_npc() [8/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1108  {
1109  if( params.type == m_debug && !debug_mode ) {
1110  return;
1111  }
1112  return add_msg_player_or_npc( params, string_format( player_msg, std::forward<Args>( args )... ),
1113  string_format( npc_msg, std::forward<Args>( args )... ) );
1114  }

◆ add_msg_player_or_npc() [9/14]

virtual void Creature::add_msg_player_or_npc
inline

Definition at line 756 of file creature.h.

1061  {}

◆ add_msg_player_or_npc() [10/14]

void npc::add_msg_player_or_npc ( const std::string &  player_msg,
const std::string &  npc_msg 
) const
overridevirtual

Reimplemented from Character.

Definition at line 3020 of file npc.cpp.

3022 {
3023  add_msg_if_player_sees( *this, replace_with_npc_name( npc_msg ) );
3024 }
void add_msg_if_player_sees(const tripoint &target, std::string msg)
Definition: messages.cpp:1007

References add_msg_if_player_sees(), and Creature::replace_with_npc_name().

◆ add_msg_player_or_npc() [11/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1078  {
1079  return add_msg_player_or_npc( string_format( player_msg, std::forward<Args>( args )... ),
1080  string_format( npc_msg, std::forward<Args>( args )... ) );
1081  }

◆ add_msg_player_or_npc() [12/14]

void Character::add_msg_player_or_npc
override

Definition at line 757 of file character.cpp.

863 {
864  Messages::add_msg( player_msg );
865 }

References fd_blood_veggy.

◆ add_msg_player_or_npc() [13/14]

void Creature::add_msg_player_or_npc

Definition at line 756 of file creature.cpp.

3161 {
3162  return add_msg_player_or_npc( pc.translated(), npc.translated() );
3163 }

◆ add_msg_player_or_npc() [14/14]

template<typename ... Args>
void Creature::add_msg_player_or_npc ( typename ...  Args)
inline

Definition at line 756 of file creature.h.

1084  {
1085  return add_msg_player_or_npc( string_format( player_msg, std::forward<Args>( args )... ),
1086  string_format( npc_msg, std::forward<Args>( args )... ) );
1087  }

◆ add_msg_player_or_say() [1/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1128  {
1129  return add_msg_player_or_say( string_format( player_msg, std::forward<Args>( args )... ),
1130  string_format( npc_speech, std::forward<Args>( args )... ) );
1131  }
void add_msg_player_or_say(const std::string &player_msg, const std::string &npc_speech) const override
Definition: character.cpp:879

◆ add_msg_player_or_say() [2/14]

virtual void Creature::add_msg_player_or_say
inline

Definition at line 761 of file creature.h.

1120  {}

◆ add_msg_player_or_say() [3/14]

void Creature::add_msg_player_or_say

Definition at line 761 of file creature.cpp.

3178 {
3179  return add_msg_player_or_say( params, pc.translated(), npc.translated() );
3180 }

◆ add_msg_player_or_say() [4/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1146  {
1147  if( params.type == m_debug && !debug_mode ) {
1148  return;
1149  }
1150  return add_msg_player_or_say( params, string_format( player_msg, std::forward<Args>( args )... ),
1151  string_format( npc_speech, std::forward<Args>( args )... ) );
1152  }

◆ add_msg_player_or_say() [5/14]

void Character::add_msg_player_or_say
override

Definition at line 764 of file character.cpp.

888 {
889  Messages::add_msg( params, player_msg );
890 }

◆ add_msg_player_or_say() [6/14]

void npc::add_msg_player_or_say ( const game_message_params params,
const std::string &  player_msg,
const std::string &  npc_speech 
) const
overridevirtual

Reimplemented from Character.

Definition at line 3046 of file npc.cpp.

3048 {
3049  say( npc_speech );
3050 }
void say(const char *const line, Args &&... args) const
Definition: npc.h:1025

References say().

◆ add_msg_player_or_say() [7/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1155  {
1156  if( params.type == m_debug && !debug_mode ) {
1157  return;
1158  }
1159  return add_msg_player_or_say( params, string_format( player_msg, std::forward<Args>( args )... ),
1160  string_format( npc_speech, std::forward<Args>( args )... ) );
1161  }

◆ add_msg_player_or_say() [8/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1164  {
1165  if( params.type == m_debug && !debug_mode ) {
1166  return;
1167  }
1168  return add_msg_player_or_say( params, string_format( player_msg, std::forward<Args>( args )... ),
1169  string_format( npc_speech, std::forward<Args>( args )... ) );
1170  }

◆ add_msg_player_or_say() [9/14]

virtual void Creature::add_msg_player_or_say
inline

Definition at line 761 of file creature.h.

1117  {}

References Creature::reachable_zone.

◆ add_msg_player_or_say() [10/14]

void Character::add_msg_player_or_say
override

Definition at line 762 of file character.cpp.

881 {
882  Messages::add_msg( player_msg );
883 }

◆ add_msg_player_or_say() [11/14]

void npc::add_msg_player_or_say ( const std::string &  player_msg,
const std::string &  npc_speech 
) const
overridevirtual

Reimplemented from Character.

Definition at line 3040 of file npc.cpp.

3042 {
3043  say( npc_speech );
3044 }

References say().

◆ add_msg_player_or_say() [12/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1134  {
1135  return add_msg_player_or_say( string_format( player_msg, std::forward<Args>( args )... ),
1136  string_format( npc_speech, std::forward<Args>( args )... ) );
1137  }

◆ add_msg_player_or_say() [13/14]

void Creature::add_msg_player_or_say

Definition at line 761 of file creature.cpp.

3172 {
3173  return add_msg_player_or_say( pc.translated(), npc.translated() );
3174 }

◆ add_msg_player_or_say() [14/14]

template<typename ... Args>
void Creature::add_msg_player_or_say ( typename ...  Args)
inline

Definition at line 761 of file creature.h.

1140  {
1141  return add_msg_player_or_say( string_format( player_msg, std::forward<Args>( args )... ),
1142  string_format( npc_speech, std::forward<Args>( args )... ) );
1143  }

◆ add_new_mission()

void npc::add_new_mission ( mission miss)

See dialogue_chatbin::add_new_mission.

Definition at line 3052 of file npc.cpp.

3053 {
3054  chatbin.add_new_mission( miss );
3055 }
dialogue_chatbin chatbin
Definition: npc.h:1406
void add_new_mission(mission *miss)
Add a new mission to the available missions (missions).

References dialogue_chatbin::add_new_mission(), and chatbin.

Referenced by debug_menu::character_edit_menu(), talk_function::clear_mission(), talk_effect_fun::anonymous_namespace{npctalk.cpp}::f_offer_mission(), load_npc_template(), and game::reset_npc_dispositions().

◆ address_needs() [1/2]

npc_action npc::address_needs ( )

Definition at line 2038 of file npcmove.cpp.

2039 {
2040  return address_needs( ai_cache.danger );
2041 }
npc_action address_needs()
Definition: npcmove.cpp:2038

References ai_cache, and npc_short_term_cache::danger.

Referenced by avoid_friendly_fire(), and move().

◆ address_needs() [2/2]

npc_action npc::address_needs ( float  danger)

Definition at line 2418 of file npcmove.cpp.

2419 {
2420  Character &player_character = get_player_character();
2421  // rng because NPCs are not meant to be hypervigilant hawks that notice everything
2422  // and swing into action with alarming alacrity.
2423  // no sometimes they are just looking the other way, sometimes they hestitate.
2424  // ( also we can get huge performance boosts )
2425  if( one_in( 3 ) ) {
2426  healing_options try_to_fix_me = patient_assessment( *this );
2427  if( try_to_fix_me.any_true() ) {
2428  if( !use_bionic_by_id( bio_nanobots ) ) {
2429  ai_cache.can_heal = has_healing_options( try_to_fix_me );
2430  if( ai_cache.can_heal.any_true() ) {
2431  return npc_heal;
2432  }
2433  }
2434  } else {
2436  }
2437  if( static_cast<int>( get_skill_level( skill_firstaid ) ) > 0 ) {
2438  if( is_player_ally() ) {
2439  healing_options try_to_fix_other = patient_assessment( player_character );
2440  if( try_to_fix_other.any_true() ) {
2441  ai_cache.can_heal = has_healing_options( try_to_fix_other );
2442  if( ai_cache.can_heal.any_true() ) {
2443  ai_cache.ally = g->shared_from( player_character );
2444  return npc_heal_player;
2445  }
2446  }
2447  }
2448  for( const npc &guy : g->all_npcs() ) {
2449  if( &guy == this || !guy.is_ally( *this ) || guy.posz() != posz() || !sees( guy ) ) {
2450  continue;
2451  }
2452  healing_options try_to_fix_other = patient_assessment( guy );
2453  if( try_to_fix_other.any_true() ) {
2454  ai_cache.can_heal = has_healing_options( try_to_fix_other );
2455  if( ai_cache.can_heal.any_true() ) {
2456  ai_cache.ally = g->shared_from( guy );
2457  return npc_heal_player;
2458  }
2459  }
2460  }
2461  }
2462  }
2463 
2464  if( one_in( 3 ) ) {
2465  if( get_perceived_pain() >= 15 ) {
2467  return npc_use_painkiller;
2468  }
2469  } else {
2471  }
2472  }
2473 
2474  if( one_in( 3 ) && can_reload_current() ) {
2475  return npc_reload;
2476  }
2477 
2478  if( one_in( 3 ) ) {
2479  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s decided to look into reloading items.", name );
2480  item_location reloadable = find_reloadable();
2481  if( reloadable ) {
2482  do_reload( reloadable );
2483  return npc_noop;
2484  }
2485  }
2486 
2487  // Extreme thirst or hunger, bypass safety check.
2488  if( get_thirst() > 80 ||
2490  if( consume_food_from_camp() ) {
2491  return npc_noop;
2492  }
2493  if( consume_food() ) {
2494  return npc_noop;
2495  }
2496  }
2497  //Hallucinations have a chance of disappearing each turn
2498  if( is_hallucination() && one_in( 25 ) ) {
2499  die( nullptr );
2500  }
2501 
2502  if( danger > NPC_DANGER_VERY_LOW ) {
2503  return npc_undecided;
2504  }
2505 
2506  if( one_in( 3 ) && ( get_thirst() > NPC_THIRST_CONSUME ||
2507  get_hunger() > NPC_HUNGER_CONSUME ) ) {
2508  if( consume_food_from_camp() ) {
2509  return npc_noop;
2510  }
2511  if( consume_food() ) {
2512  return npc_noop;
2513  }
2514  }
2515 
2516  if( one_in( 3 ) && wants_to_recharge_cbm() && recharge_cbm() ) {
2517  return npc_noop;
2518  }
2519 
2520  if( can_do_pulp() ) {
2521  if( !activity ) {
2524  }
2525  return npc_player_activity;
2526  } else if( find_corpse_to_pulp() ) {
2527  move_to_next();
2528  return npc_noop;
2529  }
2530 
2531  if( one_in( 3 ) && adjust_worn() ) {
2532  return npc_noop;
2533  }
2534 
2535  const auto could_sleep = [&]() {
2536  if( danger <= 0.01 ) {
2538  return true;
2539  }
2540  if( is_walking_with() && player_character.in_sleep_state() &&
2542  return true;
2543  }
2544  }
2545  return false;
2546  };
2547  // TODO: More risky attempts at sleep when exhausted
2548  if( could_sleep() ) {
2549  if( !is_player_ally() ) {
2550  // TODO: Make tired NPCs handle sleep offscreen
2551  set_sleepiness( 0 );
2552  return npc_undecided;
2553  }
2554 
2557  return npc_sleep;
2558  }
2559  if( player_character.in_sleep_state() ) {
2560  // TODO: "Guard me while I sleep" command
2561  return npc_sleep;
2562  }
2563  }
2564  // TODO: Mutation & trait related needs
2565  // e.g. finding glasses; getting out of sunlight if we're an albino; etc.
2566 
2567  return npc_undecided;
2568 }
player_activity activity
Definition: character.h:2709
int get_sleepiness() const
Definition: character.cpp:4604
void set_sleepiness(int nsleepiness)
Definition: character.cpp:4554
bool in_sleep_state() const override
Definition: character.cpp:9307
int get_perceived_pain() const override
Returns perceived pain (reduced with painkillers)
int get_stored_kcal() const
Getter for need values exclusive to characters.
Definition: character.cpp:4375
float get_skill_level(const skill_id &ident) const
Definition: character.cpp:3428
stomach_contents stomach
Definition: character.h:2728
int get_healthy_kcal() const
Definition: character.cpp:4470
int get_hunger() const
Definition: character.cpp:4481
void assign_activity(const activity_id &type, int moves=calendar::INDEFINITELY_LONG, int index=-1, int pos=INT_MIN, const std::string &name="")
Definition: character.cpp:8935
int posz() const
Definition: creature.h:317
A lightweight handle to an item independent of it's location Unlike a raw pointer can be (de-)seriali...
Definition: item_location.h:29
bool can_reload_current()
Can reload currently wielded gun?
Definition: npcmove.cpp:2146
item_location find_reloadable()
Has a gun or magazine that can be reloaded.
Definition: npcmove.cpp:2108
bool is_walking_with() const
Definition: npc.cpp:2317
bool has_painkiller()
Definition: npc.cpp:2227
bool consume_food()
Returns true if food was consumed, false otherwise.
Definition: npcmove.cpp:4615
bool is_hallucination() const override
Definition: npc.h:911
bool can_do_pulp()
Returns true if NPC can do pulp in this turn.
Definition: npcmove.cpp:3977
bool wants_to_recharge_cbm()
Definition: npcmove.cpp:2276
bool took_painkiller() const
Definition: npc.cpp:2232
std::optional< tripoint_abs_ms > pulp_location
Definition: npc.h:1384
bool consume_food_from_camp()
Definition: npcmove.cpp:4543
bool deactivate_bionic_by_id(const bionic_id &cbm_id, bool eff_only=false)
Definition: npcmove.cpp:2262
void do_reload(const item_location &it)
Definition: npcmove.cpp:5350
void move_to_next()
Definition: npcmove.cpp:3148
bool find_corpse_to_pulp()
Returns true if it finds one.
Definition: npcmove.cpp:3889
int get_thirst() const override
Definition: npc.cpp:3740
bool recharge_cbm()
Definition: npcmove.cpp:2299
bool adjust_worn()
Definition: npcmove.cpp:5393
healing_options patient_assessment(const Character &c)
Definition: npcmove.cpp:2381
healing_options has_healing_options()
Definition: npc.cpp:2151
npc_follower_rules rules
Definition: npc.h:1408
bool use_bionic_by_id(const bionic_id &cbm_id, bool eff_only=false)
Definition: npcmove.cpp:2248
void die(Creature *killer) override
Empty function.
Definition: npc.cpp:2790
tripoint_abs_ms placement
int get_calories() const
Definition: stomach.cpp:442
std::unique_ptr< game > g
Definition: game.cpp:382
const int INDEFINITELY_LONG
A number that represents the longest possible action.
@ DF_NPC_ITEMAI
Definition: debug.h:269
constexpr float NPC_DANGER_VERY_LOW
Definition: npc.h:62
static const bionic_id bio_painkiller("bio_painkiller")
static constexpr int NPC_HUNGER_CONSUME
Definition: npcmove.cpp:163
static const bionic_id bio_nanobots("bio_nanobots")
static constexpr int NPC_THIRST_CONSUME
Definition: npcmove.cpp:161
@ npc_sleep
Definition: npcmove.cpp:169
@ npc_reload
Definition: npcmove.cpp:169
@ npc_noop
Definition: npcmove.cpp:179
@ npc_undecided
Definition: npcmove.cpp:167
@ npc_heal_player
Definition: npcmove.cpp:173
@ npc_player_activity
Definition: npcmove.cpp:185
@ npc_use_painkiller
Definition: npcmove.cpp:171
@ npc_heal
Definition: npcmove.cpp:171
static const activity_id ACT_PULP("ACT_PULP")
static const skill_id skill_firstaid("firstaid")
bool any_true() const
Definition: npc.cpp:2132
bool has_flag(ally_rule test, bool check_override=true) const
Definition: npc.cpp:3634
healing_options can_heal
Definition: npc.h:570
weak_ptr_fast< Creature > ally
Definition: npc.h:569

References ACT_PULP, activate_bionic_by_id(), Character::activity, add_msg_debug, adjust_worn(), ai_cache, allow_sleep, npc_short_term_cache::ally, healing_options::any_true(), Character::assign_activity(), bio_nanobots, bio_painkiller, can_do_pulp(), npc_short_term_cache::can_heal, can_reload_current(), consume_food(), consume_food_from_camp(), deactivate_bionic_by_id(), debugmode::DF_NPC_ITEMAI, die(), do_reload(), find_corpse_to_pulp(), find_reloadable(), g, stomach_contents::get_calories(), Character::get_healthy_kcal(), Character::get_hunger(), Character::get_perceived_pain(), get_player_character(), Character::get_skill_level(), Character::get_sleepiness(), Character::get_stored_kcal(), get_thirst(), npc_follower_rules::has_flag(), has_healing_options(), has_painkiller(), Character::in_sleep_state(), calendar::INDEFINITELY_LONG, is_hallucination(), is_player_ally(), is_walking_with(), MASSIVE_SLEEPINESS, move_to_next(), Character::name, NPC_DANGER_VERY_LOW, npc_heal, npc_heal_player, NPC_HUNGER_CONSUME, npc_noop, npc_player_activity, npc_reload, npc_sleep, NPC_THIRST_CONSUME, npc_undecided, npc_use_painkiller, one_in(), patient_assessment(), player_activity::placement, Creature::posz(), pulp_location, recharge_cbm(), rules, Character::sees(), Character::set_sleepiness(), skill_firstaid, Character::stomach, TIRED, took_painkiller(), use_bionic_by_id(), and wants_to_recharge_cbm().

◆ address_player()

npc_action npc::address_player ( )

Definition at line 2570 of file npcmove.cpp.

2571 {
2572  Character &player_character = get_player_character();
2573  if( ( attitude == NPCATT_TALK || attitude == NPCATT_RECOVER_GOODS ) && sees( player_character ) ) {
2574  if( player_character.in_sleep_state() ) {
2575  // Leave sleeping characters alone.
2576  return npc_undecided;
2577  }
2578  if( rl_dist( pos(), player_character.pos() ) <= 6 ) {
2579  return npc_talk_to_player; // Close enough to talk to you
2580  } else {
2581  if( one_in( 10 ) ) {
2582  say( chat_snippets().snip_lets_talk.translated() );
2583  }
2584  return npc_follow_player;
2585  }
2586  }
2587 
2588  if( attitude == NPCATT_MUG && sees( player_character ) ) {
2589  if( one_in( 3 ) ) {
2590  say( chat_snippets().snip_mug_dontmove.translated() );
2591  }
2592  return npc_mug_player;
2593  }
2594 
2595  if( attitude == NPCATT_WAIT_FOR_LEAVE ) {
2596  patience--;
2597  if( patience <= 0 ) {
2598  patience = 0;
2600  return npc_noop;
2601  }
2602  return npc_undecided;
2603  }
2604 
2605  if( attitude == NPCATT_FLEE_TEMP ) {
2606  return npc_flee;
2607  }
2608 
2609  if( attitude == NPCATT_LEAD ) {
2610  if( rl_dist( pos(), player_character.pos() ) >= 12 || !sees( player_character ) ) {
2611  int intense = get_effect_int( effect_catch_up );
2612  if( intense < 10 ) {
2613  say( chat_snippets().snip_keep_up.translated() );
2614  add_effect( effect_catch_up, 5_turns );
2615  return npc_pause;
2616  } else {
2617  say( chat_snippets().snip_im_leaving_you.translated() );
2619  return npc_pause;
2620  }
2621  } else if( has_omt_destination() ) {
2622  return npc_goto_destination;
2623  } else { // At goal. Now, waiting on nearby player
2624  return npc_pause;
2625  }
2626  }
2627  return npc_undecided;
2628 }
int get_effect_int(const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID()) const
Returns the intensity of the matching effect.
Definition: creature.cpp:1872
void set_attitude(npc_attitude new_attitude)
Definition: npc.cpp:3551
const dialogue_chatbin_snippets & chat_snippets() const
Definition: npc.cpp:3805
bool has_omt_destination() const
Definition: npcmove.cpp:4790
@ NPCATT_FLEE_TEMP
Definition: npc.h:125
@ NPCATT_TALK
Definition: npc.h:108
@ NPCATT_LEAD
Definition: npc.h:112
@ NPCATT_WAIT_FOR_LEAVE
Definition: npc.h:116
@ NPCATT_MUG
Definition: npc.h:115
@ NPCATT_KILL
Definition: npc.h:117
@ NPCATT_RECOVER_GOODS
Definition: npc.h:126
@ npc_goto_destination
Definition: npcmove.cpp:176
@ npc_talk_to_player
Definition: npcmove.cpp:174
@ npc_pause
Definition: npcmove.cpp:168
@ npc_flee
Definition: npcmove.cpp:172
@ npc_mug_player
Definition: npcmove.cpp:174
@ npc_follow_player
Definition: npcmove.cpp:173
static const efftype_id effect_catch_up("catch_up")

References Creature::add_effect(), attitude, chat_snippets(), effect_catch_up, Creature::get_effect_int(), get_player_character(), has_omt_destination(), Character::in_sleep_state(), npc_flee, npc_follow_player, npc_goto_destination, npc_mug_player, npc_noop, npc_pause, npc_talk_to_player, npc_undecided, NPCATT_FLEE_TEMP, NPCATT_KILL, NPCATT_LEAD, NPCATT_MUG, NPCATT_NULL, NPCATT_RECOVER_GOODS, NPCATT_TALK, NPCATT_WAIT_FOR_LEAVE, one_in(), patience, Creature::pos(), rl_dist(), say(), Character::sees(), and set_attitude().

Referenced by move().

◆ adjust_worn()

bool npc::adjust_worn ( )

Definition at line 5393 of file npcmove.cpp.

5394 {
5395  bool any_broken = false;
5396  for( const bodypart_id &bp : get_all_body_parts() ) {
5397  if( is_limb_broken( bp ) ) {
5398  any_broken = true;
5399  break;
5400  }
5401  }
5402 
5403  if( !any_broken ) {
5404  return false;
5405  }
5406 
5407  return worn.adjust_worn( *this );
5408 }
bool is_limb_broken(const bodypart_id &limb) const
Returns true if the limb is broken.
Definition: character.cpp:2149
std::vector< bodypart_id > get_all_body_parts(get_body_part_flags=get_body_part_flags::none) const
Returns body parts this creature have.
Definition: creature.cpp:2627
bool adjust_worn(npc &guy)
Definition: npcmove.cpp:5410
bodypart_id bp
Definition: creature.h:238

References outfit::adjust_worn(), bp, Creature::get_all_body_parts(), Character::is_limb_broken(), and Character::worn.

Referenced by address_needs().

◆ aim()

void npc::aim ( const Target_attributes target_attributes)

Definition at line 2798 of file npcmove.cpp.

2799 {
2801  double aim_amount = weapon ? aim_per_move( *weapon, recoil ) : 0.0;
2802  const aim_mods_cache aim_cache = gen_aim_mods_cache( *weapon );
2803  while( aim_amount > 0 && recoil > 0 && moves > 0 ) {
2804  moves--;
2805  recoil -= aim_amount;
2806  recoil = std::max( 0.0, recoil );
2807  aim_amount = aim_per_move( *weapon, recoil, target_attributes, { std::ref( aim_cache ) } );
2808  }
2809 }
double recoil
Definition: character.h:1117
double aim_per_move(const item &gun, double recoil, const Target_attributes &target_attributes=Target_attributes(), std::optional< std::reference_wrapper< const aim_mods_cache >> aim_cache=std::nullopt) const
Definition: character.cpp:1087
aim_mods_cache gen_aim_mods_cache(const item &gun) const
Definition: character.cpp:935
item weapon
Definition: character.h:2715

References Character::aim_per_move(), Character::gen_aim_mods_cache(), Character::get_wielded_item(), max(), Creature::moves, Character::recoil, and Character::weapon.

Referenced by execute_action(), move_pause(), and npc_attack_gun::use().

◆ alt_attack()

bool npc::alt_attack ( )

Definition at line 4176 of file npcmove.cpp.

4177 {
4179  return false;
4180  }
4181 
4182  Creature *critter = current_target();
4183  if( critter == nullptr ) {
4184  // This function shouldn't be called...
4185  debugmsg( "npc::alt_attack() called with no target" );
4186  move_pause();
4187  return false;
4188  }
4189 
4190  tripoint tar = critter->pos();
4191 
4192  const int dist = rl_dist( pos(), tar );
4193  item *used = nullptr;
4194  // Remember if we have an item that is dangerous to hold
4195  bool used_dangerous = false;
4196 
4197  // TODO: The active bomb with shortest fuse should be thrown first
4198  const auto check_alt_item = [&used, &used_dangerous, dist, this]( item * it ) {
4199  if( !it ) {
4200  return;
4201  }
4202 
4203  const bool dangerous = it->has_flag( flag_NPC_THROW_NOW );
4204  if( !dangerous && used_dangerous ) {
4205  return;
4206  }
4207 
4208  // Not alt attack
4209  if( !dangerous && !it->has_flag( flag_NPC_ALT_ATTACK ) ) {
4210  return;
4211  }
4212 
4213  // TODO: Non-thrown alt items
4214  if( !dangerous && throw_range( *it ) < dist ) {
4215  return;
4216  }
4217 
4218  // Low priority items
4219  if( !dangerous && used != nullptr ) {
4220  return;
4221  }
4222 
4223  used = it;
4224  used_dangerous = used_dangerous || dangerous;
4225  };
4226 
4227  check_alt_item( &*get_wielded_item() );
4228  const auto inv_all = items_with( []( const item & ) {
4229  return true;
4230  } );
4231  for( item *it : inv_all ) {
4232  // TODO: Cached values - an itype slot maybe?
4233  check_alt_item( it );
4234  }
4235 
4236  if( used == nullptr ) {
4237  return false;
4238  }
4239 
4240  // Are we going to throw this item?
4241  if( !used->active && used->has_flag( flag_NPC_ACTIVATE ) ) {
4242  activate_item( *used );
4243  // Note: intentional lack of return here
4244  // We want to ignore player-centric rules to avoid carrying live explosives
4245  // TODO: Non-grenades
4246  }
4247 
4248  // We are throwing it!
4249  int conf = confident_throw_range( *used, critter );
4250  const bool wont_hit = wont_hit_friend( tar, *used, true );
4251  if( dist <= conf && wont_hit ) {
4252  npc_throw( *this, *used, tar );
4253  return true;
4254  }
4255 
4256  if( wont_hit ) {
4257  // Within this block, our chosen target is outside of our range
4258  update_path( tar );
4259  move_to_next(); // Move towards the target
4260  }
4261 
4262  // Danger of friendly fire
4263  if( !wont_hit && !used_dangerous ) {
4264  // Safe to hold on to, for now
4265  // Maneuver around player
4267  return true;
4268  }
4269 
4270  map &here = get_map();
4271  creature_tracker &creatures = get_creature_tracker();
4272  // We need to throw this live (grenade, etc) NOW! Pick another target?
4273  for( int dist = 2; dist <= conf; dist++ ) {
4274  for( const tripoint &pt : here.points_in_radius( pos(), dist ) ) {
4275  const monster *const target_ptr = creatures.creature_at<monster>( pt );
4276  int newdist = rl_dist( pos(), pt );
4277  // TODO: Change "newdist >= 2" to "newdist >= safe_distance(used)"
4278  if( newdist <= conf && newdist >= 2 && target_ptr &&
4279  wont_hit_friend( pt, *used, true ) ) {
4280  // Friendlyfire-safe!
4281  ai_cache.target = g->shared_from( *target_ptr );
4282  if( !one_in( 100 ) ) {
4283  // Just to prevent infinite loops...
4284  if( alt_attack() ) {
4285  return true;
4286  }
4287  }
4288  return false;
4289  }
4290  }
4291  }
4292  /* If we have reached THIS point, there's no acceptable monster to throw our
4293  * grenade or whatever at. Since it's about to go off in our hands, better to
4294  * just chuck it as far away as possible--while being friendly-safe.
4295  */
4296  int best_dist = 0;
4297  for( int dist = 2; dist <= conf; dist++ ) {
4298  for( const tripoint &pt : here.points_in_radius( pos(), dist ) ) {
4299  int new_dist = rl_dist( pos(), pt );
4300  if( new_dist > best_dist && wont_hit_friend( pt, *used, true ) ) {
4301  best_dist = new_dist;
4302  tar = pt;
4303  }
4304  }
4305  }
4306  /* Even if tar.x/tar.y didn't get set by the above loop, throw it anyway. They
4307  * should be equal to the original location of our target, and risking friendly
4308  * fire is better than holding on to a live grenade / whatever.
4309  */
4310  npc_throw( *this, *used, tar );
4311  return true;
4312 }
int throw_range(const item &) const
Maximum thrown range with a given item, taking all active effects into account.
Definition: character.cpp:5937
T * creature_at(const tripoint &p, bool allow_hallucination=false)
Returns the Creature at the given location.
Definition: item.h:196
bool active
Definition: item.h:3212
bool has_flag(const flag_id &flag) const
Definition: item.cpp:7578
Manage and cache data about a part of the map.
Definition: map.h:346
tripoint_range< tripoint > points_in_radius(const tripoint &center, size_t radius, size_t radiusz=0) const
Definition: map.cpp:10109
void activate_item(item &it)
Definition: npcmove.cpp:4314
bool update_path(const tripoint &p, bool no_bashing=false, bool force=true)
Tries to find path to p.
Definition: npcmove.cpp:2811
bool wont_hit_friend(const tripoint &tar, const item &it, bool throwing) const
Definition: npcmove.cpp:2715
void avoid_friendly_fire()
Definition: npcmove.cpp:3167
bool alt_attack()
Definition: npcmove.cpp:4176
int confident_throw_range(const item &, Creature *) const
Definition: npcmove.cpp:2703
void move_pause()
Definition: npcmove.cpp:3372
const Creature * current_target() const
Definition: npcmove.cpp:5096
std::vector< const item * > items_with(const std::function< bool(const item &)> &filter) const
Definition: visitable.cpp:330
creature_tracker & get_creature_tracker()
Definition: game.cpp:13827
#define debugmsg(...)
Debug message of level D_ERROR and class D_MAIN, also includes the source file name and line,...
Definition: debug.h:69
const flag_id flag_NPC_ALT_ATTACK("NPC_ALT_ATTACK")
const flag_id flag_NPC_THROW_NOW("NPC_THROW_NOW")
const flag_id flag_NPC_ACTIVATE("NPC_ACTIVATE")
map & get_map()
Definition: game.cpp:13822
static void npc_throw(npc &np, item &it, const tripoint &pos)
Definition: npcmove.cpp:4156
weak_ptr_fast< Creature > target
Definition: npc.h:567

References activate_item(), item::active, ai_cache, avoid_friendly_fire(), confident_throw_range(), creature_tracker::creature_at(), current_target(), debugmsg, flag_NPC_ACTIVATE, flag_NPC_ALT_ATTACK, flag_NPC_THROW_NOW, g, get_creature_tracker(), get_map(), Character::get_wielded_item(), npc_follower_rules::has_flag(), item::has_flag(), is_hallucination(), is_player_ally(), visitable::items_with(), move_pause(), move_to_next(), npc_throw(), one_in(), map::points_in_radius(), Creature::pos(), rl_dist(), rules, npc_short_term_cache::target, Character::throw_range(), update_path(), use_grenades, and wont_hit_friend().

◆ apply_ownership_to_inv()

void npc::apply_ownership_to_inv ( )

Definition at line 764 of file npc.cpp.

765 {
766  for( item *&e : inv_dump() ) {
767  e->set_owner( *this );
768  }
769 }
std::vector< item * > inv_dump()
Definition: character.cpp:8656

References Character::inv_dump().

Referenced by set_fac().

◆ as_npc() [1/2]

const npc* npc::as_npc ( ) const
inlineoverridevirtual

Reimplemented from Creature.

Definition at line 811 of file npc.h.

811  {
812  return this;
813  }

◆ as_npc() [2/2]

npc* npc::as_npc ( )
inlineoverridevirtual

Reimplemented from Creature.

Definition at line 808 of file npc.h.

808  {
809  return this;
810  }

Referenced by item::handle_pickup_ownership(), vehicle::handle_potential_theft(), and game::npc_menu().

◆ assess_danger()

void npc::assess_danger ( )

Definition at line 707 of file npcmove.cpp.

708 {
709  float highest_priority = 1.0f;
710  int hostile_count = 0; // for tallying nearby threatening enemies
711  int friendly_count = 1; // count yourself as a friendly
712  int def_radius = rules.has_flag( ally_rule::follow_close ) ? follow_distance() : 6;
713  bool npc_ranged = get_wielded_item() && get_wielded_item()->is_gun();
714 
715  if( !confident_range_cache ) {
717  }
718  // Radius we can attack without moving
719  int max_range = *confident_range_cache;
720  // Radius in which enemy threats are multiplied to avoid surrounding
721  int preferred_medium_range = std::max( max_range, 8 );
722  preferred_medium_range = std::min( preferred_medium_range, 15 );
723  // Radius in which enemy threats are hugely multiplied to encourage repositioning
724  int preferred_close_range = std::max( max_range, 1 );
725  preferred_close_range = std::min( preferred_close_range, preferred_medium_range / 2 );
726 
727  Character &player_character = get_player_character();
728  bool sees_player = sees( player_character.pos() );
729  const bool self_defense_only = rules.engagement == combat_engagement::NO_MOVE ||
731  const bool no_fighting = rules.has_flag( ally_rule::forbid_engage );
732  const bool must_retreat = rules.has_flag( ally_rule::follow_close ) &&
733  !too_close( pos(), player_character.pos(), follow_distance() ) &&
734  !is_guarding();
735 
736  if( is_player_ally() ) {
738  def_radius = std::max( 6, max_range );
739  } else if( self_defense_only ) {
740  def_radius = max_range;
741  } else if( no_fighting ) {
742  def_radius = 1;
743  }
744  }
745  mem_combat.engagement_distance = def_radius;
746 
747  const auto ok_by_rules = [max_range, def_radius, this, &player_character]( const Creature & c,
748  int dist, int scaled_dist ) {
749  // If we're forbidden to attack, no need to check engagement rules
751  return false;
752  }
753  switch( rules.engagement ) {
755  return false;
757  // Either close to player or close enough that we can reach it and close to us
758  return ( dist <= max_range && scaled_dist <= def_radius * 0.5 ) ||
759  too_close( c.pos(), player_character.pos(), def_radius );
761  return c.get_hp() <= average_damage_dealt();
763  return c.has_effect( effect_hit_by_player );
766  return dist <= max_range;
768  return true;
769  }
770 
771  return true;
772  };
773  std::map<direction, float> cur_threat_map;
774  // start with a decayed version of last turn's map
775  for( direction threat_dir : npc_threat_dir ) {
776  cur_threat_map[ threat_dir ] = 0.25f * ai_cache.threat_map[ threat_dir ];
777  }
778  map &here = get_map();
779  // cache string_id -> int_id conversion before hot loop
781  // first, check if we're about to be consumed by fire
782  // `map::get_field` uses `field_cache`, so in general case (no fire) it provides an early exit
783  for( const tripoint &pt : here.points_in_radius( pos(), 6 ) ) {
784  if( pt == pos() || !here.get_field( pt, fd_fire ) ||
786  continue;
787  }
788  int dist = rl_dist( pos(), pt );
789  cur_threat_map[direction_from( pos(), pt )] += 2.0f * ( NPC_MONSTER_DANGER_MAX - dist );
790  if( dist < 3 && !has_effect( effect_npc_fire_bad ) ) {
791  warn_about( "fire_bad", 1_minutes );
792  add_effect( effect_npc_fire_bad, 5_turns );
793  path.clear();
794  }
795  }
796 
797  // find our Character friends and enemies
798  const bool clairvoyant = clairvoyance();
799  for( const npc &guy : g->all_npcs() ) {
800  if( &guy == this ) {
801  continue;
802  }
803  if( !clairvoyant && !here.has_potential_los( pos(), guy.pos() ) ) {
804  continue;
805  }
806 
808  ai_cache.friends.emplace_back( g->shared_from( guy ) );
809  } else if( attitude_to( guy ) != Attitude::NEUTRAL && sees( guy.pos() ) ) {
810  ai_cache.hostile_guys.emplace_back( g->shared_from( guy ) );
811  }
812  }
813  if( is_friendly( player_character ) && sees_player ) {
814  ai_cache.friends.emplace_back( g->shared_from( player_character ) );
815  } else if( sees_player && is_enemy() && sees( player_character ) ) {
816  // Unlike allies, hostile npcs should not see invisible players
817  ai_cache.hostile_guys.emplace_back( g->shared_from( player_character ) );
818  }
819 
820  for( const monster &critter : g->all_monsters() ) {
821  if( !clairvoyant && !here.has_potential_los( pos(), critter.pos() ) ) {
822  continue;
823  }
824  Creature::Attitude att = critter.attitude_to( *this );
825  if( att == Attitude::FRIENDLY ) {
826  ai_cache.friends.emplace_back( g->shared_from( critter ) );
827  friendly_count += 1;
828  continue;
829  }
830  if( att != Attitude::HOSTILE && ( critter.friendly || !is_enemy() ) ) {
831  ai_cache.neutral_guys.emplace_back( g->shared_from( critter ) );
832  continue;
833  }
834  if( !sees( critter ) ) {
835  continue;
836  }
837 
838  ai_cache.hostile_guys.emplace_back( g->shared_from( critter ) );
839  // warn and consider the odds for distant enemies
840  int dist = rl_dist( pos(), critter.pos() );
841  float critter_threat = evaluate_monster( critter, dist );
842 
843  // ignore targets behind glass even if we can see them
844  if( !clear_shot_reach( pos(), critter.pos(), false ) ) {
845  if( is_enemy() || !critter.friendly ) {
846  // still warn about enemies behind impassable glass walls, but not as often.
848  "%s ignored %s because there's an obstacle in between. Might warn about it.",
849  name, critter.type->nname() );
850  if( critter_threat > 2 * ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
851  warn_about( "monster", 10_minutes, critter.type->nname(), dist, critter.pos() );
852  }
853  } else {
855  "%s ignored %s because there's an obstacle in between, and it's not worth warning about.",
856  name, critter.type->nname() );
857  }
858  continue;
859  }
860 
861  if( is_enemy() || !critter.friendly ) {
862  mem_combat.assess_enemy += critter_threat;
863  if( critter_threat > ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
864  warn_about( "monster", 10_minutes, critter.type->nname(), dist, critter.pos() );
865  }
866  if( dist < preferred_medium_range ) {
867  hostile_count += 1;
869  "<color_light_gray>%s added %s to nearby hostile count. Total: %i</color>", name,
870  critter.type->nname(), hostile_count );
871  }
872  if( dist <= preferred_close_range ) {
873  mem_combat.swarm_count += 1;
875  "<color_light_gray>%s added %s to swarm count. Total: %i</color>",
876  name, critter.type->nname(), mem_combat.swarm_count );
877  }
878  }
879  if( must_retreat || no_fighting ) {
880  continue;
881  }
882 
884  "%s assessed threat of critter %s as %1.2f.",
885  name, critter.type->nname(), critter_threat );
886  ai_cache.total_danger += critter_threat;
887  float scaled_distance = std::max( 1.0f, dist / critter.speed_rating() );
888 
889  // don't ignore monsters that are too close or too close to an ally if we can move
890  bool is_too_close = dist <= def_radius;
891  for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
892  if( is_too_close || self_defense_only ) {
893  break;
894  }
895  // HACK: Bit of a dirty hack - sometimes shared_from, returns nullptr or bad weak_ptr for
896  // friendly NPC when the NPC is riding a creature - I don't know why.
897  // so this skips the bad weak_ptrs, but this doesn't functionally change the AI Priority
898  // because the horse the NPC is riding is still in the ai_cache.friends vector,
899  // so either one would count as a friendly for this purpose.
900  if( guy.lock() ) {
901  is_too_close |= too_close( critter.pos(), guy.lock()->pos(), def_radius );
902  }
903  }
904  // ignore distant monsters that our rules prevent us from attacking
905  if( !is_too_close && is_player_ally() && !ok_by_rules( critter, dist, scaled_distance ) ) {
906  continue;
907  }
908  // prioritize the biggest, nearest threats, or the biggest threats that are threatening
909  // us or an ally
910  float priority = std::max( critter_threat - 2.0f * ( scaled_distance - 1.0f ),
911  is_too_close ? critter_threat : 0.0f );
912  cur_threat_map[direction_from( pos(), critter.pos() )] += priority;
913  if( priority > highest_priority ) {
914  highest_priority = priority;
915  ai_cache.target = g->shared_from( critter );
916  ai_cache.danger = critter_threat;
917  }
918  }
919 
920  if( mem_combat.assess_enemy == 0.0 && ai_cache.hostile_guys.empty() ) {
921  if( mem_combat.panic > 0 ) {
922  mem_combat.panic -= 1;
923  }
925  return;
926  }
927 
928  // Warn about sufficiently risky nearby hostiles
929  const auto handle_hostile = [&]( const Character & foe, float foe_threat,
930  const std::string & bogey, const std::string & warning ) {
931  int dist = rl_dist( pos(), foe.pos() );
932  // ignore targets behind glass even if we can see them
933  if( !clear_shot_reach( pos(), foe.pos(), false ) ) {
934  // still warn about enemies behind impassable glass walls, but not as often.
935  // since NPC threats have a higher chance of ignoring soft obstacles, we'll ignore them here.
936  if( foe_threat > 2 * ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
937  warn_about( "monster", 10_minutes, bogey, dist, foe.pos() );
938  }
939  return 0.0f;
940  } else {
941  add_msg_debug( debugmode::DF_NPC_COMBATAI, "%s ignored %s because there's an obstacle in between.",
942  name, bogey );
943  }
944  if( foe_threat > ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
945  warn_about( "monster", 10_minutes, bogey, dist, foe.pos() );
946  }
947 
948  int scaled_distance = std::max( 1, ( 100 * dist ) / foe.get_speed() );
949  ai_cache.total_danger += foe_threat / scaled_distance;
950  if( must_retreat || no_fighting ) {
951  return 0.0f;
952  }
953  bool is_too_close = dist <= def_radius;
954  for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
955  if( self_defense_only ) {
956  break;
957  }
958  is_too_close |= too_close( foe.pos(), guy.lock()->pos(), def_radius );
959  if( is_too_close ) {
960  break;
961  }
962  }
963 
964  if( !is_player_ally() || is_too_close || ok_by_rules( foe, dist, scaled_distance ) ) {
965  float priority = std::max( foe_threat - 2.0f * ( scaled_distance - 1 ),
966  is_too_close ? std::max( foe_threat, NPC_DANGER_VERY_LOW ) :
967  0.0f );
968  cur_threat_map[direction_from( pos(), foe.pos() )] += priority;
969  if( priority > highest_priority ) {
970  warn_about( warning, 1_minutes );
971  highest_priority = priority;
972  ai_cache.danger = foe_threat;
973  ai_cache.target = g->shared_from( foe );
974  }
975  }
977  "<color_light_gray>%s assessed threat of enemy %s as %1.2f. With distance vs speed ratio %i, final relative threat is </color><color_red>%1.2f</color>",
978  name, bogey, foe_threat, scaled_distance, foe_threat / scaled_distance );
979  return foe_threat;
980  };
981 
982 
983  for( const weak_ptr_fast<Creature> &guy : ai_cache.hostile_guys ) {
984  Character *foe = dynamic_cast<Character *>( guy.lock().get() );
985  if( foe && foe->is_npc() ) {
986  mem_combat.assess_enemy += handle_hostile( *foe, evaluate_character( *foe, npc_ranged ),
987  translate_marker( "bandit" ),
988  "kill_npc" );
989  }
990  }
992  "Before checking allies+player, %s assesses danger level as <color_light_red>%1.2f</color>.", name,
994  for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
995  if( !( guy.lock() && guy.lock()->is_npc() ) ) {
996  continue;
997  }
998  float guy_threat = std::max( evaluate_character( dynamic_cast<const Character &>( *guy.lock() ),
999  npc_ranged, false ), NPC_DANGER_VERY_LOW );
1000  mem_combat.assess_ally += guy_threat * 0.5f;
1002  "<color_light_gray>%s assessed friendly %s at threat level </color><color_light_blue>%1.2f.</color>",
1003  name, guy.lock()->disp_name(), guy_threat );
1004  }
1006  "Total of <color_green>%s NPC ally threat</color>: <color_light_green>%1.2f</color>.",
1008 
1009  if( sees_player ) {
1010  // Mod for the player's danger level, weight it higher if player is very close
1011  // When the player is almost adjacent, it can exceed max danger ratings, so the
1012  // NPC will try hard not to break and run while in formation.
1013  // This code should eventually remove the 'player' special case and be applied to
1014  // whoever the NPC perceives as their closest leader.
1015  float player_diff = std::max( evaluate_character( player_character, npc_ranged, is_enemy() ),
1017  int dist = rl_dist( pos(), player_character.pos() );
1018  if( is_enemy() ) {
1020  "<color_light_gray>%s identified player as an</color> <color_red>enemy</color> <color_light_gray>of threat level %1.2f</color>",
1021  name, player_diff );
1022  mem_combat.assess_enemy += handle_hostile( player_character, player_diff,
1023  translate_marker( "maniac" ),
1024  "kill_player" );
1025  } else if( is_friendly( player_character ) ) {
1027  "<color_light_gray>%s identified player as a </color><color_green>friend</color><color_light_gray> of threat level %1.2f (ily babe)",
1028  name, player_diff );
1029  if( dist <= 3 ) {
1030  player_diff = player_diff * ( 4 - dist ) / 2;
1031  mem_combat.swarm_count /= ( 4 - dist );
1032  mem_combat.assess_ally += player_diff;
1034  "<color_green>Player is %i tiles from %s.</color><color_light_gray> Adding </color><color_light_green>%1.2f to ally strength</color><color_light_gray> and bolstering morale.</color>",
1035  dist, name,
1036  player_diff );
1037  // don't try to fall back with your ranged weapon if you're in formation with the player.
1038  if( mem_combat.panic > 0 && one_in( dist ) ) {
1039  mem_combat.panic -= 1;
1040  }
1041  friendly_count += 4 - dist; // when close to the player, weight enemy groups less.
1042  } else {
1044  "<color_light_gray>%s sees friendly player,</color> <color_light_green>adding %1.2f</color><color_light_gray> to ally strength.</color>",
1045  name, player_diff * 0.5f );
1046  mem_combat.assess_ally += player_diff * 0.5f;
1047  }
1048  ai_cache.friends.emplace_back( g->shared_from( player_character ) );
1049  }
1050  }
1052  "<color_light_blue>After checking player</color><color_light_gray>, %s assesses enemy level as </color><color_yellow>%1.2f</color><color_light_gray>, ally level at </color><color_light_green>%1.2f</color>",
1054 
1055 
1056  // gotta rename cowardice modifier now.
1057  // This bit scales the assessments of enemies and allies so that the NPC weights their own skills a little higher.
1058  // It's likely to get deprecated in a while?
1060  //Figure our own health more heavily here, because it doens't matter how tough our friends are if we're dying.
1062 
1063  // Swarm assessment. Do a flat scale up your assessment if you're outnumbered.
1064  // Hostile_count counts enemies within a range of 8 who exceed the NPC's bravery, mitigated
1065  // how much pain they're currently experiencing. This means a very brave NPC might ignore
1066  // large crowds of minor creatures, until they start getting hurt.
1067  if( hostile_count > friendly_count ) {
1068  mem_combat.assess_enemy *= std::max( hostile_count / static_cast<float>( friendly_count ), 1.0f );
1070  "Crowd adjustment: <color_light_gray>%s set danger level to </color>%1.2f<color_light_gray> after counting </color><color_yellow>%i major hostiles</color><color_light_gray> vs </color><color_light_green>%i friendlies.</color>",
1071  name, mem_combat.assess_enemy, hostile_count, friendly_count );
1072  }
1073 
1075  float my_diff = evaluate_self( npc_ranged ) * 0.5f;
1077  "%s assesses own final strength as %1.2f.", name, my_diff );
1078  mem_combat.assess_ally += my_diff;
1080  "%s rates total <color_yellow>enemy strength %1.2f</color>, <color_light_green>ally strength %1.2f</color>.",
1082  add_msg_debug( debugmode::DF_NPC, "Enemy Danger: %1f, Ally Strength: %2f.", mem_combat.assess_enemy,
1084  }
1085  // update the threat cache
1086  for( size_t i = 0; i < 8; i++ ) {
1087  direction threat_dir = npc_threat_dir[i];
1088  direction dir_right = npc_threat_dir[( i + 1 ) % 8];
1089  direction dir_left = npc_threat_dir[( i + 7 ) % 8 ];
1090  ai_cache.threat_map[threat_dir] = cur_threat_map[threat_dir] + 0.1f *
1091  ( cur_threat_map[dir_right] + cur_threat_map[dir_left] );
1092  }
1093  if( mem_combat.assess_enemy <= 2.0f ) {
1094  ai_cache.danger_assessment = -10.0f + 5.0f *
1095  mem_combat.assess_enemy; // Low danger if no monsters around
1096  } else {
1098  }
1099 }
int clairvoyance() const
Returns the distance the player can see through walls.
Definition: character.cpp:1333
bool is_npc() const override
Definition: character.h:538
int get_speed() const override
Definition: character.cpp:4192
Attitude
Simplified attitude towards any creature: hostile - hate, want to kill, etc.
Definition: creature.h:352
bool has_flag(const std::string &flag, const tripoint &p) const
Definition: map.cpp:3077
field_entry * get_field(const tripoint &p, const field_type_id &type)
Get field of specific type at point.
Definition: map.cpp:6516
bool has_potential_los(const tripoint &from, const tripoint &to) const
A pre-filter for bresenham LOS.
Definition: map.cpp:10509
Attitude attitude_to(const Creature &other) const override
Attitude (of this creature) towards another creature.
Definition: npc.cpp:2386
float average_damage_dealt()
Definition: npc.cpp:2506
std::optional< int > confident_range_cache
Definition: npc.h:1413
bool has_faction_relationship(const Character &you, npc_factions::relationship flag) const
Definition: npc.cpp:2249
bool is_enemy() const
Definition: npc.cpp:2352
void invalidate_range_cache()
Definition: npc.cpp:1383
bool is_friendly(const Character &p) const
Definition: npc.cpp:2302
int follow_distance() const
Definition: npc.cpp:2534
bool is_guarding() const
Definition: npc.cpp:2366
float evaluate_character(const Character &candidate, bool my_gun, bool enemy)
Definition: npcmove.cpp:484
float evaluate_self(bool my_gun)
Definition: npcmove.cpp:588
float evaluate_monster(const monster &target, int dist) const
rates how dangerous a target is
Definition: npcmove.cpp:467
direction direction_from(const coords::coord_point< Point, Origin, Scale, LhsInBounds > &loc1, const coords::coord_point< Point, Origin, Scale, RhsInBounds > &loc2)
Definition: coordinates.h:790
const field_type_str_id fd_fire("fd_fire")
static constexpr double c
Definition: magic.cpp:1568
std::weak_ptr< T > weak_ptr_fast
Definition: memory_fast.h:17
@ DF_NPC
Definition: debug.h:267
@ watch_your_back
Definition: faction.h:51
constexpr float NPC_COWARDICE_MODIFIER
Definition: npc.h:65
constexpr float NPC_MONSTER_DANGER_MAX
Definition: npc.h:63
static bool too_close(const tripoint &critter_pos, const tripoint &ally_pos, const int def_radius)
Definition: npcmove.cpp:682
static const efftype_id effect_hit_by_player("hit_by_player")
static bool clear_shot_reach(const tripoint &from, const tripoint &to, bool check_ally=true)
Definition: npcmove.cpp:242
combat_engagement engagement
Definition: npc.h:506
float total_danger
Definition: npc.h:564
std::vector< weak_ptr_fast< Creature > > hostile_guys
Definition: npc.h:587
std::vector< weak_ptr_fast< Creature > > neutral_guys
Definition: npc.h:588
std::vector< weak_ptr_fast< Creature > > friends
Definition: npc.h:589
float danger_assessment
Definition: npc.h:565
#define translate_marker(x)
Marks a string literal to be extracted for translation.
Definition: translations.h:17

References Creature::add_effect(), add_msg_debug, ai_cache, ALL, npc_combat_memory_cache::assess_ally, npc_combat_memory_cache::assess_enemy, attitude_to(), average_damage_dealt(), npc_personality::bravery, c, Character::clairvoyance(), clear_shot_reach(), CLOSE, confident_range_cache, npc_short_term_cache::danger, npc_short_term_cache::danger_assessment, debugmode::DF_NPC, debugmode::DF_NPC_COMBATAI, direction_from(), effect_hit_by_player, effect_npc_fire_bad, effect_npc_run_away, npc_follower_rules::engagement, npc_combat_memory_cache::engagement_distance, evaluate_character(), evaluate_monster(), evaluate_self(), fd_fire, follow_close, follow_distance(), forbid_engage, FREE_FIRE, Creature::FRIENDLY, npc_short_term_cache::friends, g, map::get_field(), get_map(), get_player_character(), Character::get_speed(), Character::get_wielded_item(), Creature::has_effect(), has_faction_relationship(), npc_follower_rules::has_flag(), map::has_flag(), map::has_potential_los(), HIT, Creature::HOSTILE, npc_short_term_cache::hostile_guys, invalidate_range_cache(), is_enemy(), is_friendly(), is_guarding(), item::is_gun(), Character::is_npc(), is_player_ally(), max(), mem_combat, min(), npc_combat_memory_cache::my_health, Character::name, Creature::NEUTRAL, npc_short_term_cache::neutral_guys, NO_MOVE, NONE, NPC_COWARDICE_MODIFIER, NPC_DANGER_VERY_LOW, NPC_MONSTER_DANGER_MAX, npc_threat_dir, one_in(), npc_combat_memory_cache::panic, path, personality, map::points_in_radius(), Creature::pos(), rl_dist(), rng(), rules, Character::sees(), npc_combat_memory_cache::swarm_count, npc_short_term_cache::target, TFLAG_FIRE_CONTAINER, npc_short_term_cache::threat_map, too_close(), npc_short_term_cache::total_danger, translate_marker, warn_about(), npc_factions::watch_your_back, and WEAK.

Referenced by regen_ai_cache().

◆ assigned_missions_value()

int npc::assigned_missions_value ( )

Definition at line 1661 of file npc.cpp.

1662 {
1663  int ret = 0;
1664  for( ::mission *m : chatbin.missions_assigned ) {
1665  ret += m->get_value();
1666  }
1667  return ret;
1668 }
int get_value() const
Definition: mission.cpp:734
std::vector< mission * > missions_assigned
Mission that have been assigned by this dialogue to a player character.

References chatbin, mission::get_value(), dialogue_chatbin::missions_assigned, and cata::hash64_detail::ret.

Referenced by talker_npc::parse_mod().

◆ attitude_to()

Creature::Attitude npc::attitude_to ( const Creature other) const
overridevirtual

Attitude (of this creature) towards another creature.

This might not be symmetric.

Reimplemented from Character.

Definition at line 2386 of file npc.cpp.

2387 {
2388  const auto same_as = []( const Creature * lhs, const Creature * rhs ) {
2389  return &lhs == &rhs;
2390  };
2391 
2392  for( const weak_ptr_fast<Creature> &buddy : ai_cache.friends ) {
2393  if( same_as( &other, buddy.lock().get() ) ) {
2395  }
2396  }
2397  for( const weak_ptr_fast<Creature> &enemy : ai_cache.hostile_guys ) {
2398  if( same_as( &other, enemy.lock().get() ) ) {
2400  }
2401  }
2402  for( const weak_ptr_fast<Creature> &neutral : ai_cache.neutral_guys ) {
2403  if( same_as( &other, neutral.lock().get() ) ) {
2405  }
2406  }
2407 
2408  if( other.is_npc() || other.is_avatar() ) {
2409  const Character &guy = dynamic_cast<const Character &>( other );
2410  // check faction relationships first
2412  return Attitude::HOSTILE;
2414  return Attitude::FRIENDLY;
2415  }
2416  }
2417 
2418  Character &player_character = get_player_character();
2419  if( is_player_ally() ) {
2420  // Friendly NPCs share player's alliances
2421  return player_character.attitude_to( other );
2422  }
2423 
2424  if( other.is_npc() ) {
2425  // Hostile NPCs are also hostile towards player's allies
2426  if( is_enemy() && other.attitude_to( player_character ) == Attitude::FRIENDLY ) {
2427  return Attitude::HOSTILE;
2428  }
2429 
2430  return Attitude::NEUTRAL;
2431  } else if( other.is_avatar() ) {
2432  // For now, make it symmetric.
2433  return other.attitude_to( *this );
2434  }
2435 
2436  // TODO: Get rid of the ugly cast without duplicating checks
2437  const monster &m = dynamic_cast<const monster &>( other );
2438  switch( m.attitude( this ) ) {
2439  case MATT_FOLLOW:
2440  case MATT_FPASSIVE:
2441  case MATT_IGNORE:
2442  case MATT_FLEE:
2443  if( m.has_flag( mon_flag_HIT_AND_RUN ) ) {
2444  return Attitude::HOSTILE;
2445  } else {
2446  return Attitude::NEUTRAL;
2447  }
2448  case MATT_FRIEND:
2449  return Attitude::FRIENDLY;
2450  case MATT_ATTACK:
2451  return Attitude::HOSTILE;
2452  case MATT_NULL:
2453  case NUM_MONSTER_ATTITUDES:
2454  break;
2455  }
2456 
2457  return Attitude::NEUTRAL;
2458 }
Attitude attitude_to(const Creature &other) const override
Attitude (of this creature) towards another creature.
bool has_flag(const mon_flag_id &f) const final
Definition: monster.cpp:1202
monster_attitude attitude(const Character *u=nullptr) const
Definition: monster.cpp:1496
@ MATT_FLEE
Definition: monster.h:61
@ NUM_MONSTER_ATTITUDES
Definition: monster.h:65
@ MATT_FRIEND
Definition: monster.h:59
@ MATT_FOLLOW
Definition: monster.h:63
@ MATT_ATTACK
Definition: monster.h:64
@ MATT_NULL
Definition: monster.h:58
@ MATT_IGNORE
Definition: monster.h:62
@ MATT_FPASSIVE
Definition: monster.h:60
mon_flag_id mon_flag_HIT_AND_RUN
Definition: mtype.cpp:98
@ kill_on_sight
Definition: faction.h:50

References ai_cache, monster::attitude(), Character::attitude_to(), Creature::FRIENDLY, npc_short_term_cache::friends, get_player_character(), has_faction_relationship(), monster::has_flag(), Creature::HOSTILE, npc_short_term_cache::hostile_guys, is_enemy(), is_player_ally(), npc_factions::kill_on_sight, MATT_ATTACK, MATT_FLEE, MATT_FOLLOW, MATT_FPASSIVE, MATT_FRIEND, MATT_IGNORE, MATT_NULL, mon_flag_HIT_AND_RUN, Creature::NEUTRAL, neutral, npc_short_term_cache::neutral_guys, NUM_MONSTER_ATTITUDES, other, and npc_factions::watch_your_back.

Referenced by npc_attack_melee::all_evaluations(), npc_attack_throw::all_evaluations(), assess_danger(), npc_attack_melee::evaluate(), npc_attack_throw::evaluate(), npc_attack_spell::evaluate_tripoint(), npc_attack_gun::evaluate_tripoint(), npc_attack_throw::evaluate_tripoint(), game::mon_info_update(), move_to(), print_info(), and npc_attack_melee::use().

◆ average_damage_dealt()

float npc::average_damage_dealt ( )

Definition at line 2506 of file npc.cpp.

2507 {
2509  return static_cast<float>( melee_value( weap ) );
2510 }
double melee_value(const item &weap) const
Definition: melee.cpp:2814
item & null_item_reference()
Returns a reference to a null item (see item::is_null).
Definition: item.cpp:248

References Character::get_wielded_item(), Character::melee_value(), and null_item_reference().

Referenced by assess_danger().

◆ avoid_friendly_fire()

void npc::avoid_friendly_fire ( )

Definition at line 3167 of file npcmove.cpp.

3168 {
3169  // TODO: To parameter
3170  const tripoint tar = current_target()->pos();
3171  // Calculate center of weight of friends and move away from that
3172  tripoint center;
3173  for( const auto &fr : ai_cache.friends ) {
3174  if( shared_ptr_fast<Creature> fr_p = fr.lock() ) {
3175  center += fr_p->pos();
3176  }
3177  }
3178 
3179  float friend_count = ai_cache.friends.size();
3180  center.x = std::round( center.x / friend_count );
3181  center.y = std::round( center.y / friend_count );
3182  center.z = std::round( center.z / friend_count );
3183 
3184  std::vector<tripoint> candidates = closest_points_first( pos(), 1 );
3185  candidates.erase( candidates.begin() );
3186  std::sort( candidates.begin(), candidates.end(),
3187  [&tar, &center]( const tripoint & l, const tripoint & r ) {
3188  return ( rl_dist( l, tar ) - rl_dist( l, center ) ) <
3189  ( rl_dist( r, tar ) - rl_dist( r, center ) );
3190  } );
3191 
3192  for( const tripoint &pt : candidates ) {
3193  if( can_move_to( pt ) ) {
3194  move_to( pt );
3195  return;
3196  }
3197  }
3198 
3199  /* If we're still in the function at this point, maneuvering can't help us. So,
3200  * might as well address some needs.
3201  * We pass a <danger> value of NPC_DANGER_VERY_LOW + 1 so that we won't start
3202  * eating food (or, god help us, sleeping).
3203  */
3205  if( action == npc_undecided ) {
3206  move_pause();
3207  }
3209 }
bool can_move_to(const tripoint &p, bool no_bashing=false) const
Definition: npcmove.cpp:2870
void execute_action(npc_action action)
Definition: npcmove.cpp:1565
void move_to(const tripoint &p, bool no_bashing=false, std::set< tripoint > *nomove=nullptr)
Definition: npcmove.cpp:2882
std::vector< coords::coord_point< Point, Origin, Scale > > closest_points_first(const coords::coord_point< Point, Origin, Scale > &loc, int min_dist, int max_dist)
Definition: coordinates.h:848
@ action
Definition: dialogue.h:43
std::shared_ptr< T > shared_ptr_fast
Definition: memory_fast.h:16
npc_action
Definition: npcmove.cpp:166

References action, address_needs(), ai_cache, can_move_to(), center, closest_points_first(), current_target(), execute_action(), npc_short_term_cache::friends, move_pause(), move_to(), NPC_DANGER_VERY_LOW, npc_undecided, Creature::pos(), and round().

Referenced by alt_attack(), execute_action(), npc_attack_melee::use(), npc_attack_gun::use(), and npc_attack_throw::use().

◆ basic_symbol_color()

nc_color npc::basic_symbol_color ( ) const
overridevirtual

Creature symbol color.

Implements Creature.

Definition at line 2556 of file npc.cpp.

2557 {
2558  if( attitude == NPCATT_KILL ) { // NOLINT(bugprone-branch-clone)
2559  return c_red;
2560  } else if( attitude == NPCATT_FLEE || attitude == NPCATT_FLEE_TEMP ) {
2561  return c_light_red;
2562  } else if( is_player_ally() ) {
2563  return c_green;
2564  } else if( is_walking_with() ) {
2565  return c_light_green;
2566  } else if( guaranteed_hostile() ) {
2567  return c_red;
2568  }
2569  return c_pink;
2570 }
bool guaranteed_hostile() const
Is enemy or will turn into one (can't be convinced not to attack).
Definition: npc.cpp:2312
#define c_green
Definition: color.h:20
#define c_light_green
Definition: color.h:26
#define c_pink
Definition: color.h:29
#define c_light_red
Definition: color.h:25
#define c_red
Definition: color.h:19
@ NPCATT_FLEE
Definition: npc.h:118

References attitude, c_green, c_light_green, c_light_red, c_pink, c_red, guaranteed_hostile(), is_player_ally(), is_walking_with(), NPCATT_FLEE, NPCATT_FLEE_TEMP, and NPCATT_KILL.

Referenced by overmap_ui::draw_ascii(), dialogue::opt(), and print_info().

◆ best_combat_skill()

std::pair< skill_id, int > npc::best_combat_skill ( combat_skills  subset) const

Definition at line 1033 of file npc.cpp.

1034 {
1035  std::pair<skill_id, int> highest_skill( skill_stabbing, 0 );
1036 
1037  for( const auto &p : *_skills ) {
1038  if( p.first.obj().is_combat_skill() ) {
1039  switch( subset ) {
1040  case combat_skills::ALL:
1041  break;
1043  if( p.first == skill_dodge || p.first == skill_gun || p.first == skill_melee ) {
1044  continue;
1045  }
1046  break;
1048  if( p.first == skill_dodge || p.first == skill_gun || p.first == skill_melee ||
1049  p.first == skill_unarmed || p.first == skill_launcher ) {
1050  continue;
1051  }
1052  break;
1053  }
1054 
1055  const int level = p.second.level();
1056  if( level > highest_skill.second ) {
1057  highest_skill.second = level;
1058  highest_skill.first = p.first;
1059  }
1060  }
1061  }
1062 
1063  return highest_skill;
1064 }
pimpl< SkillLevelMap > _skills
Definition: character.h:3934
static const skill_id skill_launcher("launcher")
static const skill_id skill_dodge("dodge")
static const skill_id skill_gun("gun")
static const skill_id skill_melee("melee")
static const skill_id skill_unarmed("unarmed")
static const skill_id skill_stabbing("stabbing")

References Character::_skills, ALL, NO_GENERAL, skill_dodge, skill_gun, skill_launcher, skill_melee, skill_stabbing, skill_unarmed, and WEAPONS_ONLY.

Referenced by talk_function::companion_skill_trainer(), faction_display(), and starting_weapon().

◆ bravery_check()

bool npc::bravery_check ( int  diff) const

Definition at line 2512 of file npc.cpp.

2513 {
2514  return dice( 10 + personality.bravery, 6 ) >= dice( diff, 4 );
2515 }
int dice(int number, int sides)
Definition: rng.cpp:123

References npc_personality::bravery, dice(), and personality.

◆ can_do_pulp()

bool npc::can_do_pulp ( )

Returns true if NPC can do pulp in this turn.

Definition at line 3977 of file npcmove.cpp.

3978 {
3979  if( !pulp_location ) {
3980  return false;
3981  }
3982 
3983  if( rl_dist( *pulp_location, get_location() ) > 1 || pulp_location->z() != posz() ) {
3984  return false;
3985  }
3986  return true;
3987 }
tripoint_abs_ms get_location() const
Returns the location of the creature in map square coordinates (the most detailed coordinate system),...
Definition: creature.cpp:3232

References Creature::get_location(), Creature::posz(), pulp_location, and rl_dist().

Referenced by address_needs().

◆ can_move_to()

bool npc::can_move_to ( const tripoint p,
bool  no_bashing = false 
) const

Definition at line 2870 of file npcmove.cpp.

2871 {
2872  map &here = get_map();
2873 
2874  // Allow moving into any bashable spots, but penalize them during pathing
2875  // Doors are not passable for hallucinations
2876  return( rl_dist( pos(), p ) <= 1 && here.has_floor_or_water( p ) && !g->is_dangerous_tile( p ) &&
2877  ( here.passable( p ) || ( can_open_door( p, !here.is_outside( pos() ) ) && !is_hallucination() ) ||
2878  ( !no_bashing && here.bash_rating( smash_ability(), p ) > 0 ) )
2879  );
2880 }
bool is_outside(const tripoint &p) const
Definition: map.cpp:3395
int bash_rating(int str, const tripoint &p, bool allow_floor=false) const
Returns a success rating from -1 to 10 for a given tile based on a set strength, used for AI movement...
Definition: map.cpp:3304
bool has_floor_or_water(const tripoint &p) const
Definition: map.cpp:2703
bool passable(const tripoint &p) const
Definition: map.cpp:2472
int smash_ability() const override
Definition: npc.cpp:2491
bool can_open_door(const tripoint &p, bool inside) const
Definition: npcmove.cpp:2864

References map::bash_rating(), can_open_door(), g, get_map(), map::has_floor_or_water(), is_hallucination(), map::is_outside(), map::passable(), Creature::pos(), rl_dist(), and smash_ability().

Referenced by avoid_friendly_fire(), good_escape_direction(), and move_away_from().

◆ can_open_door()

bool npc::can_open_door ( const tripoint p,
bool  inside 
) const

Definition at line 2864 of file npcmove.cpp.

2865 {
2867  get_map().open_door( *this, p, inside, true );
2868 }
bool open_door(Creature const &u, const tripoint &p, bool inside, bool check_only=false)
Definition: map.cpp:4689

References avoid_doors, get_map(), npc_follower_rules::has_flag(), is_hallucination(), map::open_door(), and rules.

Referenced by can_move_to().

◆ can_read()

bool npc::can_read ( const item book,
std::vector< std::string > &  fail_reasons 
)

Definition at line 1128 of file npc.cpp.

1129 {
1130  Character *pl = dynamic_cast<Character *>( this );
1131  if( !pl ) {
1132  return false;
1133  }
1134  read_condition_result condition = check_read_condition( book );
1135  if( condition & read_condition_result::NOT_BOOK ) {
1136  fail_reasons.push_back( string_format( _( "This %s is not good reading material." ),
1137  book.tname() ) );
1138  return false;
1139  }
1140  if( condition & read_condition_result::CANT_UNDERSTAND ) {
1141  fail_reasons.push_back( string_format( _( "I'm not smart enough to read this book." ) ) );
1142  return false;
1143  }
1144  if( condition & read_condition_result::MASTERED ) {
1145  fail_reasons.push_back( string_format( _( "I won't learn anything from this book." ) ) );
1146  return false;
1147  }
1148 
1149  // Check for conditions that disqualify us
1150  if( condition & read_condition_result::ILLITERATE ) {
1151  fail_reasons.emplace_back( _( "I can't read!" ) );
1152  } else if( condition & read_condition_result::NEED_GLASSES ) {
1153  fail_reasons.emplace_back( _( "I can't read without my glasses." ) );
1154  } else if( condition & read_condition_result::TOO_DARK ) {
1155  // Too dark to read only applies if the player can read to himself
1156  fail_reasons.emplace_back( _( "It's too dark to read!" ) );
1157  return false;
1158  }
1159  return true;
1160 }
read_condition_result
Definition: character.h:459
read_condition_result check_read_condition(const item &book) const
Helper function for get_book_reader.
std::string tname(unsigned int quantity=1, tname::segment_bitset const &segments=tname::default_tname) const
Return the (translated) item name.
Definition: item.cpp:6814

References _, CANT_UNDERSTAND, Character::check_read_condition(), ILLITERATE, MASTERED, NEED_GLASSES, NOT_BOOK, string_format(), item::tname(), and TOO_DARK.

Referenced by do_npc_read().

◆ can_reload_current()

bool npc::can_reload_current ( )

Can reload currently wielded gun?

Definition at line 2146 of file npcmove.cpp.

2147 {
2149  if( !weapon || !weapon->is_gun() || !wants_to_reload( *this, *weapon ) ) {
2150  return false;
2151  }
2152 
2153  return static_cast<bool>( find_usable_ammo( weapon ) );
2154 }
item_location find_usable_ammo(const item_location &weap)
Finds ammo the NPC could use to reload a given object.
Definition: npcmove.cpp:2156
static bool wants_to_reload(const npc &guy, const item &candidate)
Definition: npcmove.cpp:2061

References find_usable_ammo(), Character::get_wielded_item(), item::is_gun(), wants_to_reload(), and Character::weapon.

Referenced by address_needs(), check_or_use_weapon_cbm(), and evaluate_best_attack().

◆ can_take_that()

bool npc::can_take_that ( const item it)

Definition at line 3788 of file npcmove.cpp.

3789 {
3790  bool good = false;
3791 
3792  auto weight_allowed = weight_capacity() - weight_carried();
3793 
3794  if( !it.made_of_from_type( phase_id::LIQUID ) && ( it.weight() <= weight_allowed ) &&
3795  can_stash( it ) ) {
3796  good = true;
3797  }
3798 
3799  return good;
3800 }
bool can_stash(const item &it, bool ignore_pkt_settings=false)
Definition: character.cpp:1494
units::mass weight_capacity() const override
Definition: character.cpp:3197
units::mass weight_carried() const
Definition: character.cpp:3088
units::mass weight(bool include_contents=true, bool integral=false) const
Total weight of an item accounting for all contained/integrated items.
Definition: item.cpp:7081
bool made_of_from_type(phase_id phase) const
Definition: item.cpp:9268
@ good
Item permits this action.

References Character::can_stash(), good, LIQUID, item::made_of_from_type(), item::weight(), Character::weight_capacity(), and Character::weight_carried().

Referenced by anonymous_namespace{npcmove.cpp}::good_for_pickup(), and npc_pickup_from_stack().

◆ can_use_offensive_cbm()

bool npc::can_use_offensive_cbm ( ) const

Definition at line 2293 of file npcmove.cpp.

2294 {
2295  const float allowed_ratio = static_cast<int>( rules.cbm_reserve ) / 100.0f;
2296  return get_power_level() > get_max_power_level() * allowed_ratio;
2297 }
units::energy get_max_power_level() const
Definition: character.cpp:2829
units::energy get_power_level() const
Definition: character.cpp:2824
cbm_reserve_rule cbm_reserve
Definition: npc.h:509

References npc_follower_rules::cbm_reserve, Character::get_max_power_level(), Character::get_power_level(), and rules.

Referenced by activate_combat_cbms(), execute_action(), and npc_attack_melee::use().

◆ character_danger()

float npc::character_danger ( const Character u) const

◆ chat_snippets()

const dialogue_chatbin_snippets & npc::chat_snippets ( ) const

Definition at line 3805 of file npc.cpp.

3806 {
3807  if( idz.is_null() ) {
3808  static dialogue_chatbin_snippets dummy;
3809  return dummy;
3810  }
3811  return idz->snippets;
3812 }
dialogue_chatbin_snippets snippets
Definition: npc.h:1497
bool is_null() const
Returns whether this represents the id of the null-object (in which case it's the null-id).
Definition: string_id.h:322

References idz, string_id< T >::is_null(), and npc_template::snippets.

Referenced by address_player(), complain(), consume_food_from_camp(), distance_string(), dialogue::dynamic_line(), execute_action(), find_corpse_to_pulp(), find_item(), talker_npc::give_item_to(), handle_sound(), look_for_player(), move_to(), mug_player(), avatar::talk_to(), try_consume(), warn_about(), and wear_if_wanted().

◆ check_or_use_weapon_cbm()

void npc::check_or_use_weapon_cbm ( const bionic_id cbm_id)

Definition at line 623 of file bionics.cpp.

624 {
625  // if we're already using a bio_weapon, keep using it
626  if( is_using_bionic_weapon() ) {
627  return;
628  }
629  const float allowed_ratio = static_cast<int>( rules.cbm_reserve ) / 100.0f;
630  const units::energy free_power = get_power_level() - get_max_power_level() * allowed_ratio;
631  if( free_power <= 0_mJ ) {
632  return;
633  }
634 
635  int index = 0;
636  bool found = false;
637  for( bionic &i : *my_bionics ) {
638  if( i.id == cbm_id && !i.powered ) {
639  found = true;
640  break;
641  }
642  index += 1;
643  }
644  if( !found ) {
645  return;
646  }
647  bionic &bio = ( *my_bionics )[index];
648 
650  const item &weap = weapon ? *weapon : null_item_reference();
651 
652  int ammo_count = weap.ammo_remaining( this );
653  const units::energy ups_drain = weap.get_gun_ups_drain();
654  if( ups_drain > 0_kJ ) {
655  ammo_count = units::from_kilojoule( static_cast<std::int64_t>( ammo_count ) ) / ups_drain;
656  }
657 
658  // the weapon value from `weapon_value` may be different from `npc_attack_rating`
659  // to avoid NPC infinitely switch weapon,
660  // only use bionic weapon when the ammo of wielded gun has been used up
661  bool ammo_used_up = !weap.is_gun() || ( ammo_count <= 0 && !can_reload_current() );
662  if( !ammo_used_up ) {
663  return;
664  }
665 
666  if( bio.info().has_flag( json_flag_BIONIC_GUN ) ) {
667  if( !bio.has_weapon() ) {
668  debugmsg( "NPC tried to activate gun bionic \"%s\" without fake_weapon",
669  bio.info().id.str() );
670  return;
671  }
672 
673  const item cbm_weapon = bio.get_weapon();
674  bool not_allowed = !rules.has_flag( ally_rule::use_guns ) ||
675  ( rules.has_flag( ally_rule::use_silent ) && !cbm_weapon.is_silent() );
676  if( is_player_ally() && not_allowed ) {
677  return;
678  }
679 
680  const int cbm_ammo = free_power / cbm_weapon.get_gun_energy_drain();
681 
682  if( weapon_value( weap, ammo_count ) < weapon_value( cbm_weapon, cbm_ammo ) ) {
683  if( real_weapon.is_null() ) {
684  // Prevent replacing real weapon when migrating saves
685  real_weapon = weap;
686  }
687  set_wielded_item( cbm_weapon );
688  weapon_bionic_uid = bio.get_uid();
689  }
690 
691  } else if( bio.info().has_flag( json_flag_BIONIC_WEAPON ) && !weap.has_flag( flag_NO_UNWIELD ) &&
692  free_power > bio.info().power_activate ) {
693 
694  if( !bio.has_weapon() ) {
695  debugmsg( "NPC tried to activate weapon bionic \"%s\" without fake_weapon",
696  bio.info().id.str() );
697  return;
698  }
699 
700  const item cbm_weapon = bio.get_weapon();
701 
702  if( weapon_value( weap, ammo_count ) < weapon_value( cbm_weapon, 0 ) ) {
703  if( is_armed() ) {
704  stow_item( *weapon );
705  }
706  add_msg_if_player_sees( pos(), m_info, _( "%s activates their %s." ),
707  disp_name(), bio.info().name );
708 
709  set_wielded_item( cbm_weapon );
711  bio.powered = true;
712  weapon_bionic_uid = bio.get_uid();
713  }
714  }
715 }
static const json_character_flag json_flag_BIONIC_GUN("BIONIC_GUN")
static const json_character_flag json_flag_BIONIC_WEAPON("BIONIC_WEAPON")
void set_wielded_item(const item &to_wield)
Definition: character.cpp:687
void mod_power_level(const units::energy &npower)
Definition: character.cpp:2852
std::string disp_name(bool possessive=false, bool capitalize_first=false) const override
Returns either "you" or the player's name.
Definition: character.cpp:829
double weapon_value(const item &weap, int ammo=10) const
NPC-related item rating functions.
Definition: melee.cpp:2781
bool is_using_bionic_weapon() const
Definition: bionics.cpp:3429
bool is_armed() const
Returns true if the character is wielding something.
Definition: melee.cpp:192
bionic_uid weapon_bionic_uid
Definition: character.h:4087
int ammo_remaining(const Character *carrier=nullptr, bool include_linked=false) const
Quantity of ammunition currently loaded in tool, gun or auxiliary gunmod.
Definition: item.cpp:10739
bool is_null() const
Definition: item.cpp:931
units::energy get_gun_energy_drain() const
Get gun energy drain.
Definition: item.cpp:14586
units::energy get_gun_ups_drain() const
Definition: item.cpp:14601
bool is_silent() const
Whether this is a (nearly) silent gun (a tiny bit of sound is allowed).
Definition: item.cpp:9430
item real_weapon
Definition: npc.h:1460
void stow_item(item &it)
Definition: npc.cpp:1294
const std::string & str() const
Returns the identifier as plain std::string.
Definition: string_id.h:260
@ m_info
Definition: enums.h:352
const flag_id flag_NO_UNWIELD("NO_UNWIELD")
constexpr quantity< value_type, energy_in_millijoule_tag > from_kilojoule(const value_type v)
Definition: units.h:555
translation name
Definition: bionics.h:141
bool has_flag(const json_character_flag &flag) const
Definition: bionics.cpp:271
units::energy power_activate
Power cost on activation.
Definition: bionics.h:37
bionic_id id
Definition: bionics.h:49
bool has_weapon() const
Definition: bionics.cpp:2931
item get_weapon() const
Definition: bionics.cpp:2947
const bionic_data & info() const
Definition: bionics.h:217
bool powered
Definition: bionics.h:205
unsigned int get_uid() const
Definition: bionics.cpp:3463

References _, add_msg_if_player_sees(), item::ammo_remaining(), can_reload_current(), npc_follower_rules::cbm_reserve, debugmsg, Character::disp_name(), flag_NO_UNWIELD, units::from_kilojoule(), item::get_gun_energy_drain(), item::get_gun_ups_drain(), Character::get_max_power_level(), Character::get_power_level(), bionic::get_uid(), bionic::get_weapon(), Character::get_wielded_item(), npc_follower_rules::has_flag(), item::has_flag(), bionic_data::has_flag(), bionic::has_weapon(), bionic_data::id, bionic::info(), Character::is_armed(), item::is_gun(), item::is_null(), is_player_ally(), item::is_silent(), Character::is_using_bionic_weapon(), json_flag_BIONIC_GUN, json_flag_BIONIC_WEAPON, m_info, Character::mod_power_level(), Character::my_bionics, bionic_data::name, null_item_reference(), Creature::pos(), bionic_data::power_activate, bionic::powered, real_weapon, rules, Character::set_wielded_item(), stow_item(), string_id< T >::str(), use_guns, use_silent, Character::weapon, Character::weapon_bionic_uid, and Character::weapon_value().

Referenced by activate_combat_cbms().

◆ cleanup_on_no_danger()

void npc::cleanup_on_no_danger ( )

Definition at line 2375 of file npcmove.cpp.

2376 {
2379 }
void deactivate_combat_cbms()
Definition: npcmove.cpp:2221
void deactivate_combat_items()
Definition: npcmove.cpp:2364

References deactivate_combat_cbms(), and deactivate_combat_items().

Referenced by move().

◆ clear_personality_traits()

void npc::clear_personality_traits ( )

Definition at line 697 of file npc.cpp.

698 {
699  for( const trait_id &trait : get_mutations() ) {
700  if( trait.obj().personality_score ) {
701  unset_mutation( trait );
702  }
703  }
704 }
void unset_mutation(const trait_id &)
Definition: mutation.cpp:297
std::vector< trait_id > get_mutations(bool include_hidden=true, bool ignore_enchantment=false, const std::function< bool(const mutation_branch &)> &filter=nullptr) const
Get the idents of all traits/mutations.

References Character::get_mutations(), and Character::unset_mutation().

◆ closest_enemy_to_friendly_distance()

std::optional< int > npc::closest_enemy_to_friendly_distance ( ) const

Definition at line 2949 of file npc.cpp.

2950 {
2952 }
std::optional< int > closest_enemy_to_friendly_distance() const
Definition: npcmove.cpp:687

References ai_cache, and npc_short_term_cache::closest_enemy_to_friendly_distance().

Referenced by npc_attack_melee::use().

◆ complain()

bool npc::complain ( )

Definition at line 5242 of file npcmove.cpp.

5243 {
5244  static const std::string infected_string = "infected";
5245  static const std::string sleepiness_string = "sleepiness";
5246  static const std::string bite_string = "bite";
5247  static const std::string bleed_string = "bleed";
5248  static const std::string hypovolemia_string = "hypovolemia";
5249  static const std::string radiation_string = "radiation";
5250  static const std::string hunger_string = "hunger";
5251  static const std::string thirst_string = "thirst";
5252 
5253  if( !is_player_ally() || !get_player_view().sees( *this ) ) {
5254  return false;
5255  }
5256 
5257  // When infected, complain every (4-intensity) hours
5258  // At intensity 3, ignore player wanting us to shut up
5259  if( has_effect( effect_infected ) ) {
5260  const bodypart_id &bp = bp_affected( *this, effect_infected );
5261  const effect &eff = get_effect( effect_infected, bp );
5262  int intensity = eff.get_intensity();
5263  std::string talktag = chat_snippets().snip_wound_infected.translated();
5264  parse_tags( talktag, get_player_character(), *this );
5265  const std::string speech = string_format( talktag, body_part_name( bp ) );
5266  if( complain_about( infected_string, time_duration::from_hours( 4 - intensity ), speech,
5267  intensity >= 3 ) ) {
5268  // Only one complaint per turn
5269  return true;
5270  }
5271  }
5272 
5273  // When bitten, complain every hour, but respect restrictions
5274  if( has_effect( effect_bite ) ) {
5275  const bodypart_id &bp = bp_affected( *this, effect_bite );
5276  std::string talktag = chat_snippets().snip_wound_bite.translated();
5277  parse_tags( talktag, get_player_character(), *this );
5278  const std::string speech = string_format( talktag, body_part_name( bp ) );
5279  if( complain_about( bite_string, 1_hours, speech ) ) {
5280  return true;
5281  }
5282  }
5283 
5284  // When tired, complain every 30 minutes
5285  // If massively tired, ignore restrictions
5287  complain_about( sleepiness_string, 30_minutes, chat_snippets().snip_yawn.translated(),
5289  return true;
5290  }
5291 
5292  // Radiation every 10 minutes
5293  if( get_rad() > 90 ) {
5296  if( complain_about( radiation_string, 10_minutes, speech, get_rad() > 150 ) ) {
5297  return true;
5298  }
5299  } else if( !get_rad() ) {
5301  }
5302 
5303  // Hunger every 3-6 hours
5304  // Since NPCs can't starve to death, respect the rules
5305  if( get_hunger() > NPC_HUNGER_COMPLAIN &&
5306  complain_about( hunger_string,
5307  std::max( 3_hours, time_duration::from_minutes( 60 * 8 - get_hunger() ) ),
5308  chat_snippets().snip_hungry.translated() ) ) {
5309  return true;
5310  }
5311 
5312  // Thirst every 2 hours
5313  // Since NPCs can't dry to death, respect the rules
5314  if( get_thirst() > NPC_THIRST_COMPLAIN &&
5315  complain_about( thirst_string, 2_hours, chat_snippets().snip_thirsty.translated() ) ) {
5316  return true;
5317  }
5318 
5319  //Bleeding every 5 minutes
5320  if( has_effect( effect_bleed ) ) {
5321  const bodypart_id &bp = bp_affected( *this, effect_bleed );
5322  std::string speech;
5323  time_duration often;
5324  if( get_effect( effect_bleed, bp ).get_intensity() < 10 ) {
5325  std::string talktag = chat_snippets().snip_bleeding.translated();
5326  parse_tags( talktag, get_player_character(), *this );
5327  speech = string_format( talktag, body_part_name( bp ) );
5328  often = 5_minutes;
5329  } else {
5330  std::string talktag = chat_snippets().snip_bleeding_badly.translated();
5331  parse_tags( talktag, get_player_character(), *this );
5332  speech = string_format( talktag, body_part_name( bp ) );
5333  often = 1_minutes;
5334  }
5335  if( complain_about( bleed_string, often, speech ) ) {
5336  return true;
5337  }
5338  }
5339 
5340  if( has_effect( effect_hypovolemia ) ) {
5341  std::string speech = chat_snippets().snip_lost_blood.translated();
5342  if( complain_about( hypovolemia_string, 10_minutes, speech ) ) {
5343  return true;
5344  }
5345  }
5346 
5347  return false;
5348 }
std::string body_part_name(const bodypart_id &bp, int number)
Returns the matching name of the body_part token.
Definition: bodypart.cpp:791
int get_rad() const
Definition: character.cpp:6757
const effect & get_effect(const efftype_id &eff_id, const bodypart_id &bp=bodypart_str_id::NULL_ID()) const
Return the effect that matches the given arguments exactly.
Definition: creature.cpp:1852
Definition: effect.h:261
int get_intensity() const
Returns the intensity of an effect.
Definition: effect.cpp:1188
bool complain_about(const std::string &issue, const time_duration &dur, const std::string &speech, bool force=false, sounds::sound_t priority=sounds::sound_t::speech)
Definition: npcmove.cpp:5211
static constexpr time_duration from_minutes(const T m)
Definition: calendar.h:233
static constexpr time_duration from_hours(const T h)
Definition: calendar.h:237
std::string translated(int num=1) const
Returns raw string if no translation is needed, otherwise returns the translated string.
int intensity
Definition: creature.h:240
void parse_tags(std::string &phrase, const Character &u, const Character &me, const itype_id &item_type=itype_id::NULL_ID())
Definition: npctalk.cpp:2056
static constexpr int NPC_THIRST_COMPLAIN
Definition: npcmove.cpp:162
static const efftype_id effect_bleed("bleed")
static const efftype_id effect_infected("infected")
static const efftype_id effect_bite("bite")
static const bionic_id bio_radscrubber("bio_radscrubber")
static const efftype_id effect_hypovolemia("hypovolemia")
static bodypart_id bp_affected(npc &who, const efftype_id &effect_type)
Definition: npcmove.cpp:5125
static constexpr int NPC_HUNGER_COMPLAIN
Definition: npcmove.cpp:164
static std::map< std::string, std::vector< SpeechBubble > > speech
Definition: speech.cpp:12

References activate_bionic_by_id(), bio_radscrubber, body_part_name(), bp, bp_affected(), chat_snippets(), complain_about(), deactivate_bionic_by_id(), effect_bite, effect_bleed, effect_hypovolemia, effect_infected, time_duration::from_hours(), time_duration::from_minutes(), Creature::get_effect(), Character::get_hunger(), effect::get_intensity(), get_player_character(), get_player_view(), Character::get_rad(), Character::get_sleepiness(), get_thirst(), Creature::has_effect(), intensity, is_player_ally(), MASSIVE_SLEEPINESS, max(), NPC_HUNGER_COMPLAIN, NPC_THIRST_COMPLAIN, parse_tags(), Character::sees(), dialogue_chatbin_snippets::snip_bleeding, dialogue_chatbin_snippets::snip_bleeding_badly, dialogue_chatbin_snippets::snip_lost_blood, dialogue_chatbin_snippets::snip_radiation_sickness, dialogue_chatbin_snippets::snip_wound_bite, dialogue_chatbin_snippets::snip_wound_infected, speech, string_format(), TIRED, and translation::translated().

Referenced by execute_action().

◆ complain_about()

bool npc::complain_about ( const std::string &  issue,
const time_duration dur,
const std::string &  speech,
bool  force = false,
sounds::sound_t  priority = sounds::sound_t::speech 
)

Definition at line 5211 of file npcmove.cpp.

5213 {
5214  // Don't have a default constructor for time_point, so accessing it in the
5215  // complaints map is a bit difficult, those lambdas should cover it.
5216  const auto complain_since = [this]( const std::string & key, const time_duration & d ) {
5217  const auto iter = complaints.find( key );
5218  return iter == complaints.end() || iter->second < calendar::turn - d;
5219  };
5220  const auto set_complain_since = [this]( const std::string & key ) {
5221  const auto iter = complaints.find( key );
5222  if( iter == complaints.end() ) {
5223  complaints.emplace( key, calendar::turn );
5224  } else {
5225  iter->second = calendar::turn;
5226  }
5227  };
5228 
5229  // Don't wake player up with non-serious complaints
5230  // Stop complaining while asleep
5231  const bool do_complain = force || ( rules.has_flag( ally_rule::allow_complain ) &&
5233 
5234  if( complain_since( issue, dur ) && do_complain ) {
5235  say( speech, priority );
5236  set_complain_since( issue );
5237  return true;
5238  }
5239  return false;
5240 }
std::map< std::string, time_point > complaints
Definition: npc.h:1346
bool force
Definition: creature.h:241
time_duration dur
Definition: creature.h:237

References allow_complain, complaints, dur, force, get_player_character(), npc_follower_rules::has_flag(), Character::in_sleep_state(), rules, say(), speech, and calendar::turn.

Referenced by complain(), consume_food_from_camp(), execute_action(), look_for_player(), Character::process_effects(), and warn_about().

◆ confidence_mult()

double npc::confidence_mult ( ) const

Definition at line 2654 of file npcmove.cpp.

2655 {
2656  if( !is_player_ally() ) {
2657  return 1.0f;
2658  }
2659 
2660  switch( rules.aim ) {
2662  return emergency() ? 1.5f : 1.0f;
2663  case aim_rule::SPRAY:
2664  return 2.0f;
2665  case aim_rule::PRECISE:
2666  return emergency() ? 1.0f : 0.75f;
2668  return 0.5f;
2669  }
2670 
2671  return 1.0f;
2672 }
bool emergency() const
Definition: npc.cpp:2517
@ WHEN_CONVENIENT
@ STRICTLY_PRECISE
aim_rule aim
Definition: npc.h:507

References npc_follower_rules::aim, emergency(), is_player_ally(), PRECISE, rules, SPRAY, STRICTLY_PRECISE, and WHEN_CONVENIENT.

Referenced by confident_gun_mode_range(), and confident_throw_range().

◆ confident_gun_mode_range()

int npc::confident_gun_mode_range ( const gun_mode gun,
int  at_recoil 
) const

Definition at line 2687 of file npcmove.cpp.

2688 {
2689  if( !gun || gun.melee() ) {
2690  return 0;
2691  }
2692 
2693  // Same calculation as in @ref item::info
2694  // TODO: Extract into common method
2695  double max_dispersion = get_weapon_dispersion( *( gun.target ) ).max() + at_recoil;
2696  double even_chance_range = range_with_even_chance_of_good_hit( max_dispersion );
2697  double confident_range = even_chance_range * confidence_mult();
2698  add_msg_debug( debugmode::DF_NPC, "confident_gun (%s<=%.2f) at %.1f", gun.tname(), confident_range,
2699  max_dispersion );
2700  return std::max<int>( confident_range, 1 );
2701 }
dispersion_sources get_weapon_dispersion(const item &obj) const
Returns a weapon's modified dispersion value.
Definition: ranged.cpp:2290
double max() const
Definition: dispersion.cpp:31
double confidence_mult() const
Definition: npcmove.cpp:2654
int range_with_even_chance_of_good_hit(int dispersion)
Definition: ranged.cpp:577

References add_msg_debug, confidence_mult(), debugmode::DF_NPC, Character::get_weapon_dispersion(), gun, dispersion_sources::max(), and range_with_even_chance_of_good_hit().

Referenced by confident_shoot_range(), and npc_attack_gun::use().

◆ confident_shoot_range()

int npc::confident_shoot_range ( const item it,
int  at_recoil 
) const

Definition at line 2674 of file npcmove.cpp.

2675 {
2676  int res = 0;
2677  if( !it.is_gun() ) {
2678  return res;
2679  }
2680 
2681  for( const auto &m : it.gun_all_modes() ) {
2682  res = std::max( res, confident_gun_mode_range( m.second, recoil ) );
2683  }
2684  return res;
2685 }
std::map< gun_mode_id, gun_mode > gun_all_modes() const
Get all possible modes for this gun inclusive of any attached gunmods.
Definition: item.cpp:11361
int confident_gun_mode_range(const gun_mode &gun, int at_recoil) const
Definition: npcmove.cpp:2687

References confident_gun_mode_range(), item::gun_all_modes(), item::is_gun(), max(), and Character::recoil.

Referenced by invalidate_range_cache(), and wont_hit_friend().

◆ confident_throw_range()

int npc::confident_throw_range ( const item thrown,
Creature target 
) const

Definition at line 2703 of file npcmove.cpp.

2704 {
2705  double average_dispersion = throwing_dispersion( thrown, target ) / 2.0;
2706  double even_chance_range = ( target == nullptr ? 0.5 : target->ranged_target_size() ) /
2707  average_dispersion;
2708  double confident_range = even_chance_range * confidence_mult();
2709  add_msg_debug( debugmode::DF_NPC, "confident_throw_range == %d",
2710  static_cast<int>( confident_range ) );
2711  return static_cast<int>( confident_range );
2712 }
int throwing_dispersion(const item &to_throw, Creature *critter=nullptr, bool is_blind_throw=false) const
Dispersion of a thrown item, against a given target, taking into account whether or not the throw was...
Definition: ranged.cpp:1183
double ranged_target_size() const
Size of the target this creature presents to ranged weapons.
Definition: ranged.cpp:547

References add_msg_debug, confidence_mult(), debugmode::DF_NPC, Creature::ranged_target_size(), and Character::throwing_dispersion().

Referenced by alt_attack(), and wont_hit_friend().

◆ consume_food()

bool npc::consume_food ( )

Returns true if food was consumed, false otherwise.

Definition at line 4615 of file npcmove.cpp.

4616 {
4617  float best_weight = 0.0f;
4618  item *best_food = nullptr;
4619  bool consumed = false;
4620  int want_hunger = std::max( 0, get_hunger() );
4621  int want_quench = std::max( 0, get_thirst() );
4622 
4623  const std::vector<item *> inv_food = cache_get_items_with( "is_food", &item::is_food );
4624 
4625  if( inv_food.empty() ) {
4626  if( !is_player_ally() ) {
4627  // TODO: Remove this and let player "exploit" hungry NPCs
4628  set_hunger( 0 );
4629  set_thirst( 0 );
4630  }
4631  } else {
4632  for( item * const &food_item : inv_food ) {
4633  float cur_weight = rate_food( *food_item, want_hunger, want_quench );
4634  // Note: will_eat is expensive, avoid calling it if possible
4635  if( cur_weight > best_weight && will_eat( *food_item ).success() ) {
4636  best_weight = cur_weight;
4637  best_food = food_item;
4638  }
4639  }
4640 
4641  // consume doesn't return a meaningful answer, we need to compare moves
4642  if( best_food != nullptr ) {
4643  const time_duration &consume_time = get_consume_time( *best_food );
4644  consumed = consume( item_location( *this, best_food ) ) != trinary::NONE;
4645  if( consumed ) {
4646  // TODO: Message that "X begins eating Y?" Right now it appears to the player
4647  // that "Urist eats a carp roast" and then stands still doing nothing
4648  // for a while.
4649  mod_moves( -to_moves<int>( consume_time ) );
4650  } else {
4651  debugmsg( "%s failed to consume %s", get_name(), best_food->tname() );
4652  }
4653  }
4654 
4655  }
4656 
4657  return consumed;
4658 }
std::vector< item * > cache_get_items_with(const itype_id &type, const std::function< bool(item &)> &do_and_check_func=return_true< item >)
Returns all items with the given flag and/or that pass the given boolean item function,...
Definition: character.cpp:9494
time_duration get_consume_time(const item &it) const
ret_val< edible_rating > will_eat(const item &food, bool interactive=false) const
Same as can_eat, but takes consequences into account.
void set_hunger(int nhunger)
Definition: character.cpp:4493
std::string get_name() const override
Definition: character.cpp:5731
void set_thirst(int nthirst)
Definition: character.cpp:4536
trinary consume(item_location loc, bool force=false)
Used for eating object at a location.
void mod_moves(int nmoves)
Definition: creature.cpp:2008
static float rate_food(const item &it, int want_nutr, int want_quench)
Definition: npcmove.cpp:4450

References Character::cache_get_items_with(), Character::consume(), debugmsg, Character::get_consume_time(), Character::get_hunger(), Character::get_name(), get_thirst(), item::is_food(), is_player_ally(), max(), Creature::mod_moves(), NONE, rate_food(), Character::set_hunger(), Character::set_thirst(), item::tname(), and Character::will_eat().

Referenced by address_needs().

◆ consume_food_from_camp()

bool npc::consume_food_from_camp ( )

Definition at line 4543 of file npcmove.cpp.

4544 {
4545  if( !is_player_ally() ) {
4546  return false;
4547  }
4548  Character &player_character = get_player_character();
4549  std::optional<basecamp *> potential_bc;
4550  for( const tripoint_abs_omt &camp_pos : player_character.camps ) {
4551  if( rl_dist( camp_pos, global_omt_location() ) < 3 ) {
4552  potential_bc = overmap_buffer.find_camp( camp_pos.xy() );
4553  if( potential_bc ) {
4554  break;
4555  }
4556  }
4557  }
4558  if( !potential_bc ) {
4559  return false;
4560  }
4561  basecamp *bcp = *potential_bc;
4562  if( get_thirst() > 40 && bcp->has_water() ) {
4563  complain_about( "camp_water_thanks", 1_hours,
4564  chat_snippets().snip_camp_water_thanks.translated(), false );
4565  // TODO: Stop skipping the stomach for this, actually put the water in there.
4566  set_thirst( 0 );
4567  return true;
4568  }
4569  faction *yours = player_character.get_faction();
4570 
4571  int current_kcals = get_stored_kcal() + stomach.get_calories() + guts.get_calories();
4572  int kcal_threshold = get_healthy_kcal() * 19 / 20;
4573  if( get_hunger() > 0 && current_kcals < kcal_threshold ) {
4574  // Try to eat a bit more than the bare minimum so that we're not eating every 5 minutes
4575  // but also don't try to eat a week's worth of food in one sitting
4576  int desired_kcals = std::min( static_cast<int>( base_metabolic_rate ), std::max( 0,
4577  kcal_threshold + 100 - current_kcals ) );
4578  int kcals_to_eat = std::min( desired_kcals, yours->food_supply.kcal() );
4579 
4580  if( kcals_to_eat > 0 ) {
4581  // We need food and there's some available, so let's eat it
4582  complain_about( "camp_food_thanks", 1_hours,
4583  chat_snippets().snip_camp_food_thanks.translated(), false );
4584 
4585  // Make a fake food object here to feed the NPC with, since camp calories are abstracted away
4586 
4587  // Fill up the stomach to "full" (half of capacity) but no further, to avoid NPCs vomiting
4588  // or becoming engorged
4589  units::volume filling_vol = std::max( 0_ml, stomach.capacity( *this ) / 2 - stomach.contains() );
4590 
4591  // Returns the actual amount of calories and vitamins taken from the camp's larder.
4592  nutrients nutr = bcp->camp_food_supply( -kcals_to_eat );
4593 
4595  0_ml,
4596  filling_vol,
4597  nutr
4598  } );
4599  // Ensure our hunger is satisfied so we don't try to eat again immediately.
4600  // update_stomach() usually takes care of that but it's only called once every 10 seconds for NPCs
4601  set_hunger( -1 );
4602 
4603  return true;
4604  } else {
4605  // We need food but there's none to eat :(
4606  complain_about( "camp_larder_empty", 1_hours,
4607  chat_snippets().snip_camp_larder_empty.translated(), false );
4608  return false;
4609  }
4610  }
4611 
4612  return false;
4613 }
std::set< tripoint_abs_omt > camps
Definition: character.h:2766
stomach_contents guts
Definition: character.h:2729
virtual faction * get_faction() const
Definition: character.h:768
tripoint_abs_omt global_omt_location() const
Returns the location of the creature in global overmap terrain coordinates.
Definition: creature.cpp:3242
nutrients camp_food_supply(nutrients &change)
Changes the faction food supply by change, returns the amount of kcal+vitamins consumed,...
bool has_water() const
Definition: basecamp.cpp:316
constexpr auto xy() const
Definition: coordinates.h:273
nutrients food_supply
Definition: faction.h:116
std::optional< basecamp * > find_camp(const point_abs_omt &p)
units::volume contains() const
Definition: stomach.cpp:316
units::volume capacity(const Character &owner) const
Calculates the capacity of this stomach.
Definition: stomach.cpp:305
void ingest(const food_summary &ingested)
Directly adds food to stomach contents.
Definition: stomach.cpp:321
constexpr float base_metabolic_rate
Definition: itype.h:117
overmapbuffer overmap_buffer
int kcal() const
Definition: stomach.cpp:118

References base_metabolic_rate, basecamp::camp_food_supply(), Character::camps, stomach_contents::capacity(), chat_snippets(), complain_about(), stomach_contents::contains(), overmapbuffer::find_camp(), faction_template::food_supply, stomach_contents::get_calories(), Character::get_faction(), Character::get_healthy_kcal(), Character::get_hunger(), get_player_character(), Character::get_stored_kcal(), get_thirst(), Creature::global_omt_location(), Character::guts, basecamp::has_water(), stomach_contents::ingest(), is_player_ally(), nutrients::kcal(), max(), min(), overmap_buffer, rl_dist(), Character::set_hunger(), Character::set_thirst(), Character::stomach, and coords::coord_point< Point, Origin, Scale, InBounds >::xy().

Referenced by address_needs().

◆ could_move_onto() [1/2]

bool npc::could_move_onto ( const tripoint p) const
private

Definition at line 400 of file npcmove.cpp.

401 {
402  map &here = get_map();
403  if( !here.passable( p ) ) {
404  return false;
405  }
406  if( !move_in_vehicle( const_cast<npc *>( this ), p ) ) {
407  return false;
408  }
409 
410  if( !sees_dangerous_field( p ) ) {
411  return true;
412  }
413 
414  const field fields_here = here.field_at( pos() );
415  for( const auto &e : here.field_at( p ) ) {
416  if( !is_dangerous_field( e.second ) ) {
417  continue;
418  }
419 
420  const auto *entry_here = fields_here.find_field( e.first );
421  if( entry_here == nullptr || entry_here->get_field_intensity() < e.second.get_field_intensity() ) {
422  return false;
423  }
424  }
425 
426  return true;
427 }
bool move_in_vehicle(Creature *c, const tripoint &dest_loc) const
Attempt to enter a tile in a vehicle.
Definition: character.cpp:8021
bool is_dangerous_field(const field_entry &entry) const
Returns true if the given field entry is dangerous to us.
Definition: creature.cpp:346
A variable sized collection of field entries on a given map square.
Definition: field.h:107
field_entry * find_field(const field_type_id &field_type_to_find, bool alive_only=true)
Returns a field entry corresponding to the field_type_id parameter passed in.
Definition: field.cpp:122
const field & field_at(const tripoint &p) const
Get the fields that are here.
Definition: map.cpp:6379
bool sees_dangerous_field(const tripoint &p) const
Definition: npcmove.cpp:395

References map::field_at(), field::find_field(), get_map(), Creature::is_dangerous_field(), Character::move_in_vehicle(), map::passable(), Creature::pos(), and sees_dangerous_field().

Referenced by could_move_onto(), execute_action(), move_to(), and worker_downtime().

◆ could_move_onto() [2/2]

bool npc::could_move_onto ( const tripoint_bub_ms p) const
private

Definition at line 429 of file npcmove.cpp.

430 {
431  return could_move_onto( p.raw() );
432 }
constexpr const Point & raw() const
Definition: coordinates.h:157
bool could_move_onto(const tripoint &p) const
Definition: npcmove.cpp:400

References could_move_onto(), and coords::coord_point_mut< Point, Subpoint, InBounds >::raw().

◆ current_ally() [1/2]

Creature * npc::current_ally ( )

Definition at line 5118 of file npcmove.cpp.

5119 {
5120  // TODO: As above.
5121  return ai_cache.ally.lock().get();
5122 }

References ai_cache, and npc_short_term_cache::ally.

◆ current_ally() [2/2]

const Creature * npc::current_ally ( ) const

Definition at line 5110 of file npcmove.cpp.

5111 {
5112  // TODO: Arguably we should return a shared_ptr to ensure that the returned
5113  // object stays alive while the caller uses it. Not doing that for now.
5114  return ai_cache.ally.lock().get();
5115 }

References ai_cache, and npc_short_term_cache::ally.

Referenced by execute_action().

◆ current_target() [1/2]

Creature * npc::current_target ( )

Definition at line 5104 of file npcmove.cpp.

5105 {
5106  // TODO: As above.
5107  return ai_cache.target.lock().get();
5108 }

References ai_cache, and npc_short_term_cache::target.

◆ current_target() [2/2]

const Creature * npc::current_target ( ) const

Definition at line 5096 of file npcmove.cpp.

5097 {
5098  // TODO: Arguably we should return a shared_ptr to ensure that the returned
5099  // object stays alive while the caller uses it. Not doing that for now.
5100  return ai_cache.target.lock().get();
5101 }

References ai_cache, and npc_short_term_cache::target.

Referenced by alt_attack(), avoid_friendly_fire(), enough_time_to_reload(), execute_action(), faction_display(), get_current_status(), method_of_attack(), and move().

◆ danger_assessment()

float npc::danger_assessment ( ) const

Definition at line 2501 of file npc.cpp.

2502 {
2503  return ai_cache.danger_assessment;
2504 }

References ai_cache, and npc_short_term_cache::danger_assessment.

Referenced by say().

◆ deactivate_bionic_by_id()

bool npc::deactivate_bionic_by_id ( const bionic_id cbm_id,
bool  eff_only = false 
)

Definition at line 2262 of file npcmove.cpp.

2263 {
2264  for( bionic &i : *my_bionics ) {
2265  if( i.id == cbm_id ) {
2266  if( i.powered ) {
2267  return deactivate_bionic( i, eff_only );
2268  } else {
2269  return false;
2270  }
2271  }
2272  }
2273  return false;
2274 }
bool deactivate_bionic(bionic &bio, bool eff_only=false)
Handles bionic deactivation effects of the entered bionic, returns if anything deactivated.
Definition: bionics.cpp:1211

References Character::deactivate_bionic(), and Character::my_bionics.

Referenced by address_needs(), complain(), deactivate_combat_cbms(), and move_pause().

◆ deactivate_combat_cbms()

void npc::deactivate_combat_cbms ( )

Definition at line 2221 of file npcmove.cpp.

2222 {
2223  for( const bionic_id &cbm_id : defense_cbms ) {
2224  deactivate_bionic_by_id( cbm_id );
2225  }
2227  for( const bionic_id &cbm_id : weapon_cbms ) {
2228  deactivate_bionic_by_id( cbm_id );
2229  }
2231  weapon_bionic_uid = 0;
2232 }
void deactivate_or_discharge_bionic_weapon(bool stow_real_weapon=false)
Definition: bionics.cpp:600
static const bionic_id bio_hydraulics("bio_hydraulics")

References bio_hydraulics, deactivate_bionic_by_id(), deactivate_or_discharge_bionic_weapon(), anonymous_namespace{npcmove.cpp}::defense_cbms, Character::weapon_bionic_uid, and anonymous_namespace{npcmove.cpp}::weapon_cbms.

Referenced by cleanup_on_no_danger().

◆ deactivate_combat_items()

void npc::deactivate_combat_items ( )

Definition at line 2364 of file npcmove.cpp.

2365 {
2366  worn.deactivate_combat_items( *this );
2367 }
void deactivate_combat_items(npc &guy)
Definition: npcmove.cpp:2349

References outfit::deactivate_combat_items(), and Character::worn.

Referenced by cleanup_on_no_danger().

◆ deactivate_or_discharge_bionic_weapon()

void npc::deactivate_or_discharge_bionic_weapon ( bool  stow_real_weapon = false)

Definition at line 600 of file bionics.cpp.

601 {
602  if( !is_using_bionic_weapon() ) {
603  return;
604  }
605 
606  std::optional<bionic *> bio_opt = find_bionic_by_uid( get_weapon_bionic_uid() );
607  if( !bio_opt ) {
608  debugmsg( "NPC tried to use a non-existent gun bionic with UID %d", weapon_bionic_uid );
609  return;
610  }
611 
612  bionic &bio = **bio_opt;
613 
614  if( bio.powered ) {
615  deactivate_bionic( bio );
616  } else {
617  if( bio.info().has_flag( json_flag_BIONIC_GUN ) ) {
618  discharge_cbm_weapon( false, stow_real_weapon );
619  }
620  }
621 }
bionic_uid get_weapon_bionic_uid() const
Definition: bionics.cpp:3434
std::optional< bionic * > find_bionic_by_uid(bionic_uid bio_uid) const
Finds the bionic with specified UID.
Definition: bionics.cpp:2810
void discharge_cbm_weapon(bool fired=true, bool stow_real_weapon=false)
Definition: bionics.cpp:575

References Character::deactivate_bionic(), debugmsg, discharge_cbm_weapon(), Character::find_bionic_by_uid(), Character::get_weapon_bionic_uid(), bionic_data::has_flag(), bionic::info(), Character::is_using_bionic_weapon(), json_flag_BIONIC_GUN, bionic::powered, and Character::weapon_bionic_uid.

Referenced by deactivate_combat_cbms(), and stow_item().

◆ decide_needs()

void npc::decide_needs ( )

Definition at line 1670 of file npc.cpp.

1671 {
1673  std::array<double, num_needs> needrank;
1674  for( double &elem : needrank ) {
1675  elem = 20;
1676  }
1677  if( weapon && weapon->is_gun() ) {
1678  units::energy energy_drain = weapon->get_gun_energy_drain();
1679  if( energy_drain > 0_kJ ) {
1680  units::energy energy_charges = weapon->energy_remaining( this );
1681  needrank[need_ammo] = static_cast<double>( energy_charges / energy_drain );
1682  } else {
1683  const ammotype ammo_type = weapon->ammo_type();
1684  if( ammo_type != ammotype::NULL_ID() ) {
1685  needrank[need_ammo] = get_ammo( ammo_type ).size();
1686  }
1687  }
1688  needrank[need_ammo] *= 5;
1689  }
1690  if( !base_location ) {
1691  needrank[need_safety] = 1;
1692  }
1693 
1694  const item &weap = weapon ? *weapon : null_item_reference();
1695  needrank[need_weapon] = weapon_value( weap );
1696  needrank[need_food] = 15 - get_hunger();
1697  needrank[need_drink] = 15 - get_thirst();
1698  cache_visit_items_with( "is_food", &item::is_food, [&]( const item & it ) {
1699  needrank[ need_food ] += nutrition_for( it ) / 4.0;
1700  needrank[ need_drink ] += it.get_comestible()->quench / 4.0;
1701  } );
1702  needs.clear();
1703  size_t j;
1704  bool serious = false;
1705  for( int i = 1; i < num_needs; i++ ) {
1706  if( needrank[i] < 10 ) {
1707  serious = true;
1708  }
1709  }
1710  if( !serious ) {
1711  needs.push_back( need_none );
1712  needrank[0] = 10;
1713  }
1714  for( int i = 1; i < num_needs; i++ ) {
1715  if( needrank[i] < 20 ) {
1716  for( j = 0; j < needs.size(); j++ ) {
1717  if( needrank[i] < needrank[needs[j]] ) {
1718  needs.insert( needs.begin() + j, static_cast<npc_need>( i ) );
1719  j = needs.size() + 1;
1720  }
1721  }
1722  if( j == needs.size() ) {
1723  needs.push_back( static_cast<npc_need>( i ) );
1724  }
1725  }
1726  }
1727 }
std::vector< const item * > get_ammo(const ammotype &at) const
Returns the items that are ammo and have the matching ammo type.
void cache_visit_items_with(const itype_id &type, const std::function< void(item &)> &do_func)
Applies a lambda function on all items with the given flag and/or that pass the given boolean item fu...
Definition: character.cpp:9312
int nutrition_for(const item &comest) const
Handles the nutrition value for a comestible.
units::energy energy_remaining(const Character *carrier=nullptr) const
Energy available from battery/UPS/bionics.
Definition: item.cpp:10750
const cata::value_ptr< islot_comestible > & get_comestible() const
Definition: item.cpp:14803
ammotype ammo_type() const
Ammo type of an ammo item.
Definition: item.cpp:11073
std::vector< npc_need > needs
Definition: npc.h:1412
std::optional< tripoint_abs_omt > base_location
Definition: npc.h:1374
npc_need
Definition: npc.h:199
@ need_safety
Definition: npc.h:202
@ need_weapon
Definition: npc.h:201
@ need_food
Definition: npc.h:202
@ num_needs
Definition: npc.h:203
@ need_drink
Definition: npc.h:202
@ need_none
Definition: npc.h:200
@ need_ammo
Definition: npc.h:201

References item::ammo_type(), base_location, Character::cache_visit_items_with(), item::energy_remaining(), Character::get_ammo(), item::get_comestible(), item::get_gun_energy_drain(), Character::get_hunger(), get_thirst(), Character::get_wielded_item(), item::is_food(), item::is_gun(), need_ammo, need_drink, need_food, need_none, need_safety, need_weapon, needs, string_id< ammunition_type >::NULL_ID(), null_item_reference(), num_needs, Character::nutrition_for(), Character::weapon, and Character::weapon_value().

Referenced by form_opinion(), talker_npc::get_topics(), and set_omt_destination().

◆ describe_mission()

std::string npc::describe_mission ( ) const

Definition at line 3745 of file npc.cpp.

3746 {
3747  switch( mission ) {
3748  case NPC_MISSION_SHELTER:
3749  return string_format( _( "I'm holing up here for safety. Long term, %s" ),
3751  case NPC_MISSION_SHOPKEEP:
3752  return _( "I run the shop here." );
3753  case NPC_MISSION_GUARD:
3756  return string_format( _( "Currently, I'm guarding this location. Overall, %s" ),
3758  case NPC_MISSION_ACTIVITY:
3759  return string_format( _( "Right now, I'm <current_activity>. In general, %s" ),
3762  case NPC_MISSION_NULL:
3763  return myclass.obj().get_job_description();
3764  default:
3765  debugmsg( "ERROR: Someone forgot to code an npc_mission text for mission: %d.",
3766  static_cast<int>( mission ) );
3767  return "";
3768  } // switch (mission)
3769 }
std::string get_job_description() const
Definition: npc_class.cpp:412
const T & obj() const
Returns the actual object this id refers to.
Definition: achievement.cpp:71
@ NPC_MISSION_SHELTER
Definition: npc.h:174
@ NPC_MISSION_GUARD_PATROL
Definition: npc.h:182
@ NPC_MISSION_GUARD_ALLY
Definition: npc.h:180
@ NPC_MISSION_ACTIVITY
Definition: npc.h:183
@ NPC_MISSION_GUARD
Definition: npc.h:181
@ NPC_MISSION_SHOPKEEP
Definition: npc.h:175
@ NPC_MISSION_TRAVELLING
Definition: npc.h:184

References _, debugmsg, npc_class::get_job_description(), myclass, NPC_MISSION_ACTIVITY, NPC_MISSION_GUARD, NPC_MISSION_GUARD_ALLY, NPC_MISSION_GUARD_PATROL, NPC_MISSION_NULL, NPC_MISSION_SHELTER, NPC_MISSION_SHOPKEEP, NPC_MISSION_TRAVELLING, string_id< T >::obj(), and string_format().

Referenced by talker_npc::get_job_description().

◆ deserialize()

void npc::deserialize ( const JsonObject data)
overridevirtual

Implements Character.

Definition at line 2037 of file savegame_json.cpp.

2038 {
2039  load( data );
2040 }
void load(const JsonObject &data)

References item_pocket::data, and ammo_effects::load().

Referenced by import_and_clean().

◆ die()

void npc::die ( Creature killer)
overridevirtual

Empty function.

Should always be overwritten by the appropriate player/NPC/monster version.

Reimplemented from Character.

Definition at line 2790 of file npc.cpp.

2791 {
2792  if( dead ) {
2793  // We are already dead, don't die again, note that npc::dead is
2794  // *only* set to true in this function!
2795  return;
2796  }
2797  prevent_death_reminder = false;
2798  dialogue d( get_talker_for( this ), nkiller == nullptr ? nullptr : get_talker_for( nkiller ) );
2800  if( eoc->type == eoc_type::NPC_DEATH ) {
2801  eoc->activate( d );
2802  } else {
2803  debugmsg( "Tried to use non NPC_DEATH eoc_type %s for an npc death.", eoc.c_str() );
2804  }
2805  }
2807  // Check if npc doesn't die due to EoC as a result
2808  if( prevent_death_reminder ) {
2809  prevent_death_reminder = false;
2810  if( !is_dead() ) {
2811  return;
2812  }
2813  }
2814 
2815  if( assigned_camp ) {
2816  std::optional<basecamp *> bcp = overmap_buffer.find_camp( ( *assigned_camp ).xy() );
2817  if( bcp ) {
2818  ( *bcp )->remove_assignee( getID() );
2819  }
2820  }
2821  assigned_camp = std::nullopt;
2822  // Need to unboard from vehicle before dying, otherwise
2823  // the vehicle code cannot find us
2824  if( in_vehicle ) {
2825  get_map().unboard_vehicle( pos(), true );
2826  }
2827  if( is_mounted() ) {
2828  monster *critter = mounted_creature.get();
2829  critter->remove_effect( effect_ridden );
2830  critter->mounted_player = nullptr;
2831  critter->mounted_player_id = character_id();
2832  }
2833  // if this NPC was the only member of a micro-faction, clean it up.
2834  if( my_fac ) {
2835  if( !is_fake() && !is_hallucination() ) {
2836  if( my_fac->members.size() == 1 ) {
2837  for( const item *elem : inv_dump() ) {
2838  elem->remove_owner();
2839  elem->remove_old_owner();
2840  }
2841  }
2842  my_fac->remove_member( getID() );
2843  my_fac = nullptr;
2844  }
2845  }
2846  dead = true;
2847  Character::die( nkiller );
2848 
2849  if( is_hallucination() || lifespan_end ) {
2850  add_msg_if_player_sees( *this, _( "%s disappears." ), get_name().c_str() );
2851  return;
2852  }
2853 
2854  add_msg_if_player_sees( *this, _( "%s dies!" ), get_name() );
2855 
2856  if( Character *ch = dynamic_cast<Character *>( killer ) ) {
2858  }
2859  Character &player_character = get_player_character();
2860  if( killer == &player_character ) {
2861  if( player_character.has_trait( trait_PACIFIST ) ) {
2862  add_msg( _( "A cold shock of guilt washes over you." ) );
2863  player_character.add_morale( MORALE_KILLER_HAS_KILLED, -15, 0, 1_days, 1_hours );
2864  }
2865  if( hit_by_player ) {
2866  int morale_effect = -90;
2867  // Just because you like eating people doesn't mean you love killing innocents
2868  if( player_character.has_flag( json_flag_CANNIBAL ) && morale_effect < 0 ) {
2869  morale_effect = std::min( 0, morale_effect + 50 );
2870  } // Pacifists double dip on penalties if they kill an innocent
2871  if( player_character.has_trait( trait_PACIFIST ) ) {
2872  morale_effect -= 15;
2873  }
2874  if( player_character.has_flag( json_flag_PSYCHOPATH ) ||
2875  player_character.has_flag( json_flag_SAPIOVORE ) ) {
2876  morale_effect = 0;
2877  } // Killer has the psychopath flag, so we're at +5 total. Whee!
2878  if( player_character.has_trait( trait_KILLER ) ) {
2879  morale_effect += 5;
2880  } // only god can juge me
2881  if( player_character.has_flag( json_flag_SPIRITUAL ) &&
2882  ( !player_character.has_flag( json_flag_PSYCHOPATH ) ||
2883  ( player_character.has_flag( json_flag_PSYCHOPATH ) &&
2884  player_character.has_trait( trait_KILLER ) ) ) &&
2885  !player_character.has_flag( json_flag_SAPIOVORE ) ) {
2886  if( morale_effect < 0 ) {
2887  add_msg( _( "You feel ashamed of your actions." ) );
2888  morale_effect -= 10;
2889  } // skulls for the skull throne
2890  if( morale_effect > 0 ) {
2891  add_msg( _( "You feel a sense of righteous purpose." ) );
2892  morale_effect += 5;
2893  }
2894  }
2895  if( morale_effect == 0 ) {
2896  // No morale effect
2897  } else if( morale_effect <= -50 ) {
2898  player_character.add_morale( MORALE_KILLED_INNOCENT, morale_effect, 0, 2_days, 3_hours );
2899  } else if( morale_effect > -50 && morale_effect < 0 ) {
2900  player_character.add_morale( MORALE_KILLED_INNOCENT, morale_effect, 0, 1_days, 1_hours );
2901  } else {
2902  player_character.add_morale( MORALE_KILLED_INNOCENT, morale_effect, 0, 3_hours, 7_minutes );
2903  }
2904  }
2905  }
2906 
2907  place_corpse();
2908 }
void place_corpse()
void die(Creature *nkiller) override
Empty function.
Definition: character.cpp:3569
bool in_vehicle
Definition: character.h:2693
bool is_mounted() const
Definition: character.cpp:1732
bool has_flag(const json_character_flag &flag) const
Returns true if player has a trait, bionic, effect, bodypart, or martial arts buff with a flag.
std::vector< effect_on_condition_id > death_eocs
Definition: character.h:2689
void add_morale(const morale_type &type, int bonus, int max_bonus=0, const time_duration &duration=1_hours, const time_duration &decay_start=30_minutes, bool capped=false, const itype *item_type=nullptr)
shared_ptr_fast< monster > mounted_creature
Definition: character.h:2800
character_id getID() const
Definition: character.cpp:652
bool has_trait(const trait_id &b) const override
Returns true if the player has the entered trait.
Definition: mutation.cpp:111
faction * my_fac
Definition: character.h:3959
std::optional< time_point > lifespan_end
Definition: creature.h:1196
virtual bool is_fake() const
Returns true for non-real Creatures used temporarily; i.e.
Definition: creature.cpp:1518
Creature * killer
Definition: creature.h:1194
void send(const cata::event &) const
Definition: event_bus.cpp:72
void remove_member(const character_id &guy_id)
Definition: faction.cpp:176
std::map< character_id, std::pair< std::string, bool > > members
Definition: faction.h:151
void unboard_vehicle(const vpart_reference &, Character *passenger, bool dead_passenger=false)
Definition: map.cpp:1395
Character * mounted_player
Definition: monster.h:526
character_id mounted_player_id
Definition: monster.h:527
bool prevent_death_reminder
Definition: npc.h:1466
std::optional< tripoint_abs_omt > assigned_camp
Definition: npc.h:1333
bool is_dead() const
Definition: npc.cpp:2746
@ NPC_DEATH
@ character_kills_character
event_bus & get_event_bus()
Definition: game.cpp:13832
const morale_type MORALE_KILLED_INNOCENT("morale_killed_innocent")
const morale_type MORALE_KILLER_HAS_KILLED("morale_killer_has_killed")
static const json_character_flag json_flag_CANNIBAL("CANNIBAL")
static const trait_id trait_PACIFIST("PACIFIST")
static const json_character_flag json_flag_PSYCHOPATH("PSYCHOPATH")
static const trait_id trait_KILLER("KILLER")
static const efftype_id effect_ridden("ridden")
std::unique_ptr< talker > get_talker_for(npc &guy)
Definition: npc.cpp:3814
static const json_character_flag json_flag_SPIRITUAL("SPIRITUAL")
static const json_character_flag json_flag_SAPIOVORE("SAPIOVORE")

References _, Character::add_morale(), add_msg(), add_msg_if_player_sees(), assigned_camp, character_dies, character_id, character_kills_character, dead, Character::death_eocs, debugmsg, Character::die(), effect_ridden, eoc, overmapbuffer::find_camp(), get_event_bus(), get_map(), Character::get_name(), get_player_character(), get_talker_for(), Character::getID(), Character::has_flag(), Character::has_trait(), hit_by_player, Character::in_vehicle, Character::inv_dump(), is_dead(), Creature::is_fake(), is_hallucination(), Character::is_mounted(), json_flag_CANNIBAL, json_flag_PSYCHOPATH, json_flag_SAPIOVORE, json_flag_SPIRITUAL, Creature::killer, Creature::lifespan_end, faction::members, min(), MORALE_KILLED_INNOCENT, MORALE_KILLER_HAS_KILLED, Character::mounted_creature, monster::mounted_player, monster::mounted_player_id, Character::my_fac, NPC_DEATH, overmap_buffer, Character::place_corpse(), Creature::pos(), prevent_death_reminder, Creature::remove_effect(), faction::remove_member(), event_bus::send(), trait_KILLER, trait_PACIFIST, and map::unboard_vehicle().

Referenced by address_needs(), talker_npc::die(), and on_attacked().

◆ discharge_cbm_weapon()

void npc::discharge_cbm_weapon ( bool  fired = true,
bool  stow_real_weapon = false 
)

Definition at line 575 of file bionics.cpp.

576 {
577  if( !is_using_bionic_weapon() ) {
578  return;
579  }
580 
581  item *pseudo_gun = get_wielded_item().get_item();
582  if( pseudo_gun != nullptr ) {
583  if( fired ) {
584  mod_power_level( -pseudo_gun->get_gun_bionic_drain() );
585  }
586  } else {
587  debugmsg( "NPC tried to use a non-existent bionic gun with UID %d", weapon_bionic_uid );
588  }
589 
591  real_weapon = item();
592  weapon_bionic_uid = 0;
593 
594  item *real_weapon_ptr = get_wielded_item().get_item();
595  if( stow_real_weapon && real_weapon_ptr != nullptr ) {
596  stow_item( *real_weapon_ptr );
597  }
598 }
item * get_item()
Gets the selected item or nullptr.
units::energy get_gun_bionic_drain() const
Definition: item.cpp:14609

References debugmsg, item::get_gun_bionic_drain(), item_location::get_item(), Character::get_wielded_item(), Character::is_using_bionic_weapon(), item, Character::mod_power_level(), real_weapon, Character::set_wielded_item(), stow_item(), and Character::weapon_bionic_uid.

Referenced by deactivate_or_discharge_bionic_weapon(), and execute_action().

◆ dispose_item()

bool npc::dispose_item ( item_location &&  obj,
const std::string &  prompt = std::string() 
)
overridevirtual

Drop, wear, stash or otherwise try to dispose of an item consuming appropriate moves.

Parameters
objitem to dispose of
promptoptional message to display in any menu
Returns
whether the item was successfully disposed of

Reimplemented from Character.

Definition at line 3175 of file npc.cpp.

3176 {
3177  stow_item( *obj.get_item() );
3178  return true;
3179 }

References stow_item().

◆ distance_string()

std::string npc::distance_string ( int  range) const

Definition at line 5140 of file npcmove.cpp.

5141 {
5142  if( range < 6 ) {
5144  } else if( range < 11 ) {
5146  } else if( range < 26 ) {
5148  } else {
5150  }
5151 }
translation snip_danger_close_distance

References chat_snippets(), dialogue_chatbin_snippets::snip_close_distance, dialogue_chatbin_snippets::snip_danger_close_distance, dialogue_chatbin_snippets::snip_far_distance, dialogue_chatbin_snippets::snip_medium_distance, and translation::translated().

Referenced by warn_about().

◆ do_npc_craft()

void npc::do_npc_craft ( const std::optional< tripoint > &  loc = std::nullopt,
const recipe_id goto_recipe = recipe_id() 
)

Definition at line 3132 of file crafting.cpp.

3133 {
3134  std::vector<item_location> craft_item_list;
3135  std::string dummy;
3136 
3137  visit_items( [ this, &craft_item_list, &dummy ]( item * itm, item * ) {
3138  if( itm->is_craft() && itm->get_making().npc_can_craft( dummy ) ) {
3139  item_location to_craft = item_location( *this, itm );
3140  if( !is_anyone_crafting( to_craft, this ) ) {
3141  craft_item_list.push_back( to_craft );
3142  }
3143  }
3144  return VisitResponse::NEXT;
3145  } );
3146 
3147  map &here = get_map();
3148  for( const tripoint &adj : here.points_in_radius( pos(), 1 ) ) {
3149  if( here.dangerous_field_at( adj ) ) {
3150  continue;
3151  }
3152  for( item &itm : here.i_at( adj ) ) {
3153  if( itm.is_craft() && itm.get_making().npc_can_craft( dummy ) ) {
3154  item_location to_craft = item_location( map_cursor( adj ), &itm );
3155  if( !is_anyone_crafting( to_craft, this ) ) {
3156  craft_item_list.push_back( to_craft );
3157  }
3158  }
3159  }
3160  if( const std::optional<vpart_reference> vp = here.veh_at( adj ).cargo() ) {
3161  for( item &itm : vp->items() ) {
3162  if( itm.is_craft() && itm.get_making().npc_can_craft( dummy ) ) {
3163  item_location to_craft = item_location( vehicle_cursor( vp->vehicle(), vp->part_index() ), &itm );
3164  if( !is_anyone_crafting( to_craft, this ) ) {
3165  craft_item_list.push_back( to_craft );
3166  }
3167  }
3168  }
3169  }
3170  }
3171 
3172  if( craft_item_list.empty() ) {
3173  craft( loc, goto_recipe );
3174  } else {
3175  uilist menu;
3176  menu.text = "Craft what?";
3177  menu.addentry( 0, true, MENU_AUTOASSIGN, _( "Craft new item" ) );
3178  menu.addentry( 1, true, MENU_AUTOASSIGN, _( "Work on craft" ) );
3179  menu.query();
3180 
3181  if( menu.ret == 0 ) {
3182  craft( loc, goto_recipe );
3183  } else if( menu.ret == 1 ) {
3184  int selected = 0;
3185  uilist item_selection;
3186  do {
3187  item_selection.init();
3188  item_selection.text = "Craft what?";
3189  item_selection.selected = selected;
3190  item_selection.addentry( 0, true, MENU_AUTOASSIGN, "Start crafting" );
3191  item_selection.addentry( 1, true, MENU_AUTOASSIGN, "Select all" );
3192  int index = 2;
3193 
3194  for( item_location &itm : craft_item_list ) {
3195  // set flag to craft
3196  std::string entry;
3197  bool enable = itm->get_var( "crafter", "" ) == name;
3198  if( selected == 1 ) {
3199  itm->set_var( "crafter", name );
3200  enable = true;
3201  } else if( selected == index ) {
3202  if( enable ) {
3203  itm->erase_var( "crafter" );
3204  enable = false;
3205  } else {
3206  itm->set_var( "crafter", name );
3207  enable = true;
3208  }
3209  }
3210  if( enable ) {
3211  entry = string_format( "[x] %s", itm->tname() );
3212  } else {
3213  entry = string_format( "[ ] %s", itm->tname() );
3214  }
3215  item_selection.addentry( index, true, MENU_AUTOASSIGN, entry );
3216  index++;
3217  }
3218  item_selection.query();
3219 
3220  selected = item_selection.ret;
3221  if( selected == 0 ) {
3223  }
3224  } while( selected >= 1 );
3225  }
3226  }
3227 }
VisitResponse visit_items(const std::function< VisitResponse(item *, item *)> &func) const override
Traverses this object and any child items contained using a visitor pattern.
void craft(const std::optional< tripoint > &loc=std::nullopt, const recipe_id &goto_recipe=recipe_id(), const std::string &filterstring="")
Start various types of crafts.
Definition: crafting.cpp:394
double get_var(const std::string &name, double default_value) const
Definition: item.cpp:1839
void set_var(const std::string &name, int value)
Definition: item.cpp:1809
const recipe & get_making() const
Get the stored recipe for in progress crafts.
Definition: item.cpp:14758
bool is_craft() const
Definition: item.cpp:9930
void erase_var(const std::string &name)
Erase the value of the given variable.
Definition: item.cpp:1933
bool npc_can_craft(std::string &reason) const
Definition: recipe.cpp:1317
uilist: scrolling vertical list menu
Definition: ui.h:232
int ret
Definition: ui.h:525
void addentry(const std::string &txt)
Definition: ui.cpp:1210
int selected
Definition: ui.h:526
std::string text
Definition: ui.h:419
static const activity_id ACT_MULTIPLE_CRAFT("ACT_MULTIPLE_CRAFT")
static bool is_anyone_crafting(const item_location &itm, const Character *you=nullptr)
Definition: crafting.cpp:3073
void query(bool loop=true, int timeout=-1)
Handle input and update display.
Definition: ui.cpp:1032
void init()
Sane defaults on initialization.
Definition: ui.cpp:245
const int MENU_AUTOASSIGN
Definition: ui.h:38

References item::get_making(), item::is_craft(), NEXT, recipe::npc_can_craft(), and Character::visit_items().

Referenced by talk_function::do_craft().

◆ do_npc_read()

void npc::do_npc_read ( bool  ebook = false)

Definition at line 1182 of file npc.cpp.

1183 {
1184  // Can read items from inventory or within one tile (including in vehicles)
1185  Character *npc_player = as_character();
1186  if( !npc_player ) {
1187  return;
1188  }
1189 
1190  item_location book;
1191  item_location ereader;
1192 
1193  if( !ebook ) {
1194  book = game_menus::inv::read( *npc_player );
1195  } else {
1196  ereader = game_menus::inv::ereader_to_use( *npc_player );
1197  if( !ereader ) {
1198  add_msg( _( "Never mind." ) );
1199  return;
1200  }
1201  book = game_menus::inv::ebookread( *npc_player, ereader );
1202  }
1203 
1204  if( !book ) {
1205  add_msg( _( "Never mind." ) );
1206  return;
1207  }
1208 
1209  std::vector<std::string> fail_reasons;
1210  Character *npc_character = as_character();
1211  if( !npc_character ) {
1212  return;
1213  }
1214 
1215  book = book.obtain( *npc_character );
1216  if( can_read( *book, fail_reasons ) ) {
1217  add_msg_if_player_sees( pos(), _( "%s starts reading." ), disp_name() );
1218 
1219  // NPCs can't read to other NPCs yet
1220  const time_duration time_taken = time_to_read( *book, *this );
1221 
1222  // NPCs read until they gain a level
1223  read_activity_actor actor( time_taken, book, ereader, true, getID().get_value() );
1224  assign_activity( actor );
1225 
1226  } else {
1227  for( const std::string &reason : fail_reasons ) {
1228  say( reason );
1229  }
1230  }
1231 }
Character * as_character() override
Definition: character.h:532
std::string get_value(const std::string &key) const
Definition: creature.cpp:1959
item_location obtain(Character &ch, int qty=-1)
Move an item from the location to the character inventory If the player fails to obtain the item (lik...
bool can_read(const item &book, std::vector< std::string > &fail_reasons)
Definition: npc.cpp:1128
time_duration time_to_read(const item &book, const Character &reader) const
Definition: npc.cpp:1162
item_location ereader_to_use(Character &you)
E-Book reading menu.
item_location ebookread(Character &you, item_location &ereader)
eBook reading menu.
item_location read(Character &you)
Book reading menu.

References _, add_msg(), add_msg_if_player_sees(), Character::as_character(), Character::assign_activity(), can_read(), Character::disp_name(), game_menus::inv::ebookread(), game_menus::inv::ereader_to_use(), Creature::get_value(), Character::getID(), item_location::obtain(), Creature::pos(), game_menus::inv::read(), say(), and time_to_read().

Referenced by talk_function::do_eread(), and talk_function::do_read().

◆ do_player_activity()

bool npc::do_player_activity ( )

perform a player activity, returning true if it took up the turn

Definition at line 3989 of file npcmove.cpp.

3990 {
3991  int old_moves = moves;
3992  if( moves > 200 && activity && ( activity.is_multi_type() ||
3993  activity.id() == ACT_TIDY_UP ) ) {
3994  // a huge backlog of a multi-activity type can forever loop
3995  // instead; just scan the map ONCE for a task to do, and if it returns false
3996  // then stop scanning, abandon the activity, and kill the backlog of moves.
3997  if( !generic_multi_activity_handler( activity, *this->as_character(), true ) ) {
3999  set_moves( 0 );
4000  return true;
4001  }
4002  }
4003  // the multi-activity types can sometimes cancel the activity, and return without using up any moves.
4004  // ( when they are setting a destination etc. )
4005  // normally this isn't a problem, but in the main game loop, if the NPC has a huge backlog of moves;
4006  // then each of these occurrences will nudge the infinite loop counter up by one.
4007  // ( even if other move-using things occur inbetween )
4008  // so here - if no moves are used in a multi-type activity do_turn(), then subtract a nominal amount
4009  // to satisfy the infinite loop counter.
4010  const bool multi_type = activity ? activity.is_multi_type() : false;
4011  const int moves_before = moves;
4012  while( moves > 0 && activity ) {
4013  activity.do_turn( *this );
4014  if( !is_active() ) {
4015  return true;
4016  }
4017  }
4018  if( multi_type && moves == moves_before ) {
4019  mod_moves( -1 );
4020  }
4021  /* if the activity is finished, grab any backlog or change the mission */
4022  if( !has_destination() && !activity ) {
4023  // workaround: auto resuming craft activity may cause infinite loop
4024  while( !backlog.empty() && backlog.front().id() == ACT_CRAFT ) {
4025  backlog.pop_front();
4026  }
4027  if( !backlog.empty() ) {
4028  activity = backlog.front();
4029  backlog.pop_front();
4031  } else {
4032  if( is_player_ally() ) {
4033  add_msg( m_info, string_format( _( "%s completed the assigned task." ), disp_name() ) );
4034  }
4037  // if we loaded after being out of the bubble for a while, we might have more
4038  // moves than we need, so clear them
4039  set_moves( 0 );
4040  }
4041  }
4042  return moves != old_moves;
4043 }
bool generic_multi_activity_handler(player_activity &act, Character &you, bool check_only=false)
bool has_destination() const
std::list< player_activity > backlog
Definition: character.h:2710
void set_moves(int nmoves)
Definition: creature.cpp:2012
bool is_active() const
Definition: npc.cpp:2529
activity_id current_activity_id
Definition: npc.h:1328
void revert_after_activity()
Definition: npc.cpp:927
void do_turn(Character &you)
Performs the activity for a single turn.
const activity_id & id() const
bool is_multi_type() const
static const activity_id ACT_TIDY_UP("ACT_TIDY_UP")
static const activity_id ACT_CRAFT("ACT_CRAFT")

References _, ACT_CRAFT, ACT_TIDY_UP, Character::activity, add_msg(), Character::as_character(), Character::backlog, current_activity_id, Character::disp_name(), player_activity::do_turn(), generic_multi_activity_handler(), Character::has_destination(), player_activity::id(), is_active(), player_activity::is_multi_type(), is_player_ally(), m_info, Creature::mod_moves(), Creature::moves, string_id< activity_type >::NULL_ID(), revert_after_activity(), Creature::set_moves(), and string_format().

Referenced by execute_action().

◆ do_reload()

void npc::do_reload ( const item_location it)

Definition at line 5350 of file npcmove.cpp.

5351 {
5352  if( !it ) {
5353  debugmsg( "do_reload failed: %s tried to reload a none", name );
5354  return;
5355  }
5356 
5357  item::reload_option reload_opt = select_ammo( it );
5358 
5359  if( !reload_opt ) {
5360  debugmsg( "do_reload failed: no usable ammo for %s", it->tname() );
5361  return;
5362  }
5363 
5364  // Note: we may be reloading the magazine inside, not the gun itself
5365  // Maybe TODO: allow reload functions to understand such reloads instead of const casts
5366  item &target = const_cast<item &>( *reload_opt.target );
5367  item_location &usable_ammo = reload_opt.ammo;
5368 
5369  int qty = std::max( 1, std::min( usable_ammo->charges,
5370  it->ammo_capacity( usable_ammo->ammo_data()->ammo->type ) - it->ammo_remaining() ) );
5371  int reload_time = item_reload_cost( *it, *usable_ammo, qty );
5372  // TODO: Consider printing this info to player too
5373  const std::string ammo_name = usable_ammo->tname();
5374  if( !target.reload( *this, std::move( usable_ammo ), qty ) ) {
5375  debugmsg( "do_reload failed: item %s could not be reloaded with %ld charge(s) of %s",
5376  it->tname(), qty, ammo_name );
5377  return;
5378  }
5379 
5380  mod_moves( -reload_time );
5381  recoil = MAX_RECOIL;
5382 
5383  if( get_player_view().sees( *this ) ) {
5384  add_msg( _( "%1$s reloads their %2$s." ), get_name(), it->tname() );
5385  sfx::play_variant_sound( "reload", it->typeId().str(), sfx::get_heard_volume( pos() ),
5386  sfx::get_heard_angle( pos() ) );
5387  }
5388 
5389  // Otherwise the NPC may not equip the weapon until they see danger
5390  has_new_items = true;
5391 }
int item_reload_cost(const item &it, const item &ammo, int qty) const
Calculate (but do not deduct) the number of moves required to reload an item with specified quantity ...
item_location target
Definition: item.h:561
item_location ammo
Definition: item.h:562
int ammo_capacity(const ammotype &ammo, bool include_linked=false) const
ammo capacity for a specific ammo
Definition: item.cpp:10801
itype_id typeId() const
return the unique identifier of the items underlying type
Definition: item.cpp:11850
const itype * ammo_data() const
Specific ammo data, returns nullptr if item is neither ammo nor loaded with any.
Definition: item.cpp:10995
int charges
Definition: item.h:3133
bool reload(Character &u, item_location ammo, int qty)
Reload item using ammo from location returning true if successful.
Definition: item.cpp:11612
item::reload_option select_ammo(const item_location &base, bool prompt=false, bool empty=true) override
Select suitable ammo with which to reload the item.
Definition: npcmove.cpp:2175
constexpr double MAX_RECOIL
int get_heard_volume(const tripoint &source)
Functions from sfx that do not use the SDL_mixer API at all.
Definition: sounds.cpp:2045
void play_variant_sound(const std::string &id, const std::string &variant, int volume, units::angle angle, double pitch_min=-1.0, double pitch_max=-1.0)
Definition: sounds.cpp:1999
units::angle get_heard_angle(const tripoint &source)
Definition: sounds.cpp:2058
cata::value_ptr< islot_ammo > ammo
Definition: itype.h:1212

References _, add_msg(), item::reload_option::ammo, itype::ammo, item::ammo_capacity(), item::ammo_data(), item::ammo_remaining(), item::charges, debugmsg, sfx::get_heard_angle(), sfx::get_heard_volume(), Character::get_name(), get_player_view(), has_new_items, Character::item_reload_cost(), max(), MAX_RECOIL, min(), Creature::mod_moves(), Character::name, sfx::play_variant_sound(), Creature::pos(), Character::recoil, item::reload(), Character::sees(), select_ammo(), string_id< T >::str(), item::reload_option::target, item::tname(), and item::typeId().

Referenced by address_needs(), execute_action(), and npc_attack_gun::use().

◆ drop()

void npc::drop ( const drop_locations what,
const tripoint target,
bool  stash 
)
overridevirtual

Reimplemented from Character.

Definition at line 1374 of file npc.cpp.

1376 {
1377  Character::drop( what, target, stash );
1378  // TODO: Remove the hack. Its here because npcs didn't process activities, but they do now
1379  // so is this necessary?
1380  activity.do_turn( *this );
1381 }
void drop(item_location loc, const tripoint &where)
Drops an item to the specified location.

References Character::activity, player_activity::do_turn(), and Character::drop().

◆ emergency() [1/2]

bool npc::emergency ( ) const

◆ emergency() [2/2]

bool npc::emergency ( float  danger) const

Definition at line 2522 of file npc.cpp.

2523 {
2524  return danger > ( personality.bravery * 3 * hp_percentage() ) / 100.0;
2525 }
int hp_percentage() const override
Returns overall % of HP remaining.

References npc_personality::bravery, Character::hp_percentage(), and personality.

◆ enough_time_to_reload()

bool npc::enough_time_to_reload ( const item gun) const

Definition at line 2762 of file npcmove.cpp.

2763 {
2764  int rltime = item_reload_cost( gun, item( gun.ammo_default() ),
2765  gun.ammo_capacity(
2766  item_controller->find_template( gun.ammo_default() )->ammo->type ) );
2767  const float turns_til_reloaded = static_cast<float>( rltime ) / get_speed();
2768 
2769  const Creature *target = current_target();
2770  if( target == nullptr ) {
2771  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s can't see anyone around: great time to reload.",
2772  name );
2773  return true;
2774  }
2775 
2776  const int distance = rl_dist( pos(), target->pos() );
2777  const float target_speed = target->speed_rating();
2778  const float turns_til_reached = distance / target_speed;
2779  if( target->is_avatar() || target->is_npc() ) {
2780  const Character &foe = dynamic_cast<const Character &>( *target );
2781  const item_location weapon = foe.get_wielded_item();
2782  // TODO: Allow reloading if the player has a low accuracy gun
2783  if( sees( foe ) && weapon && weapon->is_gun() && rltime > 200 &&
2784  weapon->gun_range( true ) > distance + turns_til_reloaded / target_speed ) {
2785  // Don't take longer than 2 turns if player has a gun
2786  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s is shy about reloading with &s standing right there.",
2787  name, foe.name );
2788  return false;
2789  }
2790  }
2791 
2792  // TODO: Handle monsters with ranged attacks and players with CBMs
2793  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s turns to reload: %i./nTurns til reached: %i.", name,
2794  static_cast<int>( turns_til_reloaded ), static_cast<int>( turns_til_reached ) );
2795  return turns_til_reloaded < turns_til_reached;
2796 }
virtual float speed_rating() const =0
Returns an approximate number of tiles this creature can travel per turn.
virtual bool is_avatar() const
Definition: creature.h:265
virtual bool is_npc() const
Definition: creature.h:268
int gun_range(const Character *p) const
The weapons range in map squares.
Definition: item.cpp:10648
std::unique_ptr< Item_factory > item_controller

References add_msg_debug, current_target(), debugmode::DF_NPC_ITEMAI, Character::get_speed(), Character::get_wielded_item(), gun, item::gun_range(), Creature::is_avatar(), item::is_gun(), Creature::is_npc(), item, item_controller, Character::item_reload_cost(), Character::name, Creature::pos(), rl_dist(), Character::sees(), Creature::speed_rating(), and Character::weapon.

◆ escape_explosion()

void npc::escape_explosion ( )

Definition at line 3211 of file npcmove.cpp.

3212 {
3213  if( ai_cache.dangerous_explosives.empty() ) {
3214  return;
3215  }
3216 
3217  warn_about( "explosion", 1_minutes );
3218 
3220 }
void move_away_from(const tripoint &p, bool no_bash_atk=false, std::set< tripoint > *nomove=nullptr)
Definition: npcmove.cpp:3222
std::vector< sphere > dangerous_explosives
Definition: npc.h:590

References ai_cache, npc_short_term_cache::dangerous_explosives, move_away_from(), and warn_about().

Referenced by execute_action().

◆ estimate_armour()

float npc::estimate_armour ( const Character candidate) const

Definition at line 649 of file npcmove.cpp.

650 {
651  float armour = 0.0f;
652  int armour_step;
653  int number_of_parts = 0;
654 
655  for( bodypart_id part_id : candidate.get_all_body_parts( get_body_part_flags::only_main ) ) {
656  armour_step = 0;
657  number_of_parts += 1;
658  armour_step += candidate.get_armor_type( damage_bash, part_id );
659  armour_step += candidate.get_armor_type( damage_cut, part_id );
660  armour_step += candidate.get_armor_type( damage_stab, part_id );
661  armour_step += candidate.get_armor_type( damage_bullet, part_id );
663  "<color_light_gray>%s: %s armour value for %s rated as %i.</color>", name,
664  candidate.disp_name( true ), body_part_name( part_id ), armour_step );
665  if( part_id == bodypart_id( "head" ) || part_id == bodypart_id( "torso" ) ) {
666  armour_step *= 4;
667  number_of_parts += 3;
668  }
669  // obtain an average value of the 4 armour types we checked.
670  armour += static_cast<float>( armour_step ) / 4.0f;
671  }
672  armour /= number_of_parts;
673 
675  "<color_light_gray>%s rates </color>%s total armour value: %1.2f.", name,
676  candidate.disp_name( true ), armour );
677  // this is a value we could easily cache.
678  // I don't know how to do that, I'm supposed to be a writer.
679  return armour;
680 }
int_id< body_part_type > bodypart_id
Definition: bodypart.h:32
int get_armor_type(const damage_type_id &dt, bodypart_id bp) const override
Returns overall resistance to given type on the bod part.
static const damage_type_id damage_bash("bash")
static const damage_type_id damage_bullet("bullet")
static const damage_type_id damage_cut("cut")
static const damage_type_id damage_stab("stab")

References add_msg_debug, body_part_name(), damage_bash, damage_bullet, damage_cut, damage_stab, debugmode::DF_NPC_ITEMAI, Character::disp_name(), Creature::get_all_body_parts(), Character::get_armor_type(), Character::name, and only_main.

Referenced by evaluate_character(), and evaluate_self().

◆ evaluate_best_attack()

void npc::evaluate_best_attack ( const Creature target)

Definition at line 1985 of file npcmove.cpp.

1986 {
1987  std::shared_ptr<npc_attack> best_attack;
1988  npc_attack_rating best_evaluated_attack;
1989  const auto compare = [&best_attack, &best_evaluated_attack, this, &target]
1990  ( const std::shared_ptr<npc_attack> &potential_attack ) {
1991  const npc_attack_rating evaluated = potential_attack->evaluate( *this, target );
1992  if( evaluated > best_evaluated_attack ) {
1993  best_attack = potential_attack;
1994  best_evaluated_attack = evaluated;
1995  }
1996  };
1997 
1998  // punching things is always available
1999  compare( std::make_shared<npc_attack_melee>( null_item_reference() ) );
2000  visit_items( [&compare, this]( item * it, item * ) {
2001  // you can theoretically melee with anything.
2002  compare( std::make_shared<npc_attack_melee>( *it ) );
2003  if( !is_wielding( *it ) || !it->has_flag( flag_NO_UNWIELD ) ) {
2004  compare( std::make_shared<npc_attack_throw>( *it ) );
2005  }
2006  if( !it->type->use_methods.empty() ) {
2007  compare( std::make_shared<npc_attack_activate_item>( *it ) );
2008  }
2010  for( const std::pair<const gun_mode_id, gun_mode> &mode : it->gun_all_modes() ) {
2011  if( !( mode.second.melee() || mode.second.flags.count( "NPC_AVOID" ) ||
2012  !can_use( *mode.second.target ) ||
2014  !mode.second->is_silent() ) ) ) {
2015  if( it->shots_remaining( this ) > 0 || can_reload_current() ) {
2016  compare( std::make_shared<npc_attack_gun>( *it, mode.second ) );
2017  } else {
2018  compare( std::make_shared<npc_attack_melee>( *it ) );
2019  }
2020  }
2021  }
2022  }
2023  return VisitResponse::NEXT;
2024  } );
2025  if( magic->spells().empty() ) {
2026  magic->clear_opens_spellbook_data();
2028  magic->evaluate_opens_spellbook_data();
2029  }
2030  for( const spell_id &sp : magic->spells() ) {
2031  compare( std::make_shared<npc_attack_spell>( sp ) );
2032  }
2033 
2034  ai_cache.current_attack = best_attack;
2035  ai_cache.current_attack_evaluation = best_evaluated_attack;
2036 }
bool can_use(const item &it, const item &context=item()) const
Checks if character stats and skills meet minimum requirements for the item.
Definition: character.cpp:3271
bool is_wielding(const item &target) const
Definition: character.cpp:3319
pimpl< known_magic > magic
Definition: character.h:2485
int shots_remaining(const Character *carrier) const
Quantity of shots in the gun.
Definition: item.cpp:10668
void compare(avatar &you, const std::optional< tripoint > &offset)
std::map< std::string, use_function > use_methods
Actions an instance can perform (if any) indexed by action type.
Definition: itype.h:1312
std::shared_ptr< npc_attack > current_attack
Definition: npc.h:582
npc_attack_rating current_attack_evaluation
Definition: npc.h:581

References ai_cache, can_reload_current(), Character::can_use(), game_menus::inv::compare(), npc_short_term_cache::current_attack, npc_short_term_cache::current_attack_evaluation, flag_NO_UNWIELD, get_event_bus(), Character::getID(), item::gun_all_modes(), npc_follower_rules::has_flag(), item::has_flag(), is_player_ally(), Character::is_wielding(), Character::magic, NEXT, null_item_reference(), opens_spellbook, rules, event_bus::send(), item::shots_remaining(), item::type, use_guns, itype::use_methods, use_silent, and Character::visit_items().

Referenced by method_of_attack().

◆ evaluate_best_weapon()

item * npc::evaluate_best_weapon ( ) const

Definition at line 4064 of file npcmove.cpp.

4065 {
4066  bool can_use_gun = !is_player_ally() || rules.has_flag( ally_rule::use_guns );
4068 
4070  item &weap = weapon ? *weapon : null_item_reference();
4071 
4072  // Check if there's something better to wield
4073  item *best = &weap;
4074  double best_value = evaluate_weapon( weap, can_use_gun, use_silent );
4075 
4076  // To prevent changing to barely better stuff
4077  best_value *= std::max<float>( 1.0f, ai_cache.danger_assessment / 10.0f );
4078 
4079  // Fists aren't checked below
4080  double fist_value = evaluate_weapon( null_item_reference(), can_use_gun, use_silent );
4081 
4082  if( fist_value > best_value ) {
4083  best = &null_item_reference();
4084  best_value = fist_value;
4085  }
4086 
4087  //Now check through the NPC's inventory for melee weapons, guns, or holstered items
4088  visit_items( [this, can_use_gun, use_silent, &weap, &best_value, &best]( item * node, item * ) {
4089  double weapon_value = 0.0;
4090  bool using_same_type_bionic_weapon = is_using_bionic_weapon()
4091  && node != &weap
4092  && node->type->get_id() == weap.type->get_id();
4093 
4094  if( node->is_melee() || node->is_gun() ) {
4095  weapon_value = evaluate_weapon( *node, can_use_gun, use_silent );
4096  if( weapon_value > best_value && !using_same_type_bionic_weapon ) {
4097  best = const_cast<item *>( node );
4098  best_value = weapon_value;
4099  }
4100  return VisitResponse::SKIP;
4101  } else if( node->get_use( "holster" ) && !node->empty() ) {
4102  // we just recur to the next farther down
4103  return VisitResponse::NEXT;
4104  }
4105  return VisitResponse::NEXT;
4106  } );
4107 
4108  return best;
4109 }
const use_function * get_use(const std::string &use_name) const
Returns the pointer to use_function with name use_name assigned to the type of this item or any of it...
Definition: item.cpp:11463
bool empty() const
Definition: item.cpp:15135
bool is_melee(const damage_type_id &dt) const
Is this item an effective melee weapon for the given damage type?
Definition: item.cpp:9596
double evaluate_weapon(item &maybe_weapon, bool can_use_gun, bool use_silent) const
Definition: npcmove.cpp:4045
itype_id get_id() const
Definition: itype.h:1497

References ai_cache, npc_short_term_cache::danger_assessment, item::empty(), evaluate_weapon(), itype::get_id(), item::get_use(), Character::get_wielded_item(), npc_follower_rules::has_flag(), item::is_gun(), item::is_melee(), is_player_ally(), Character::is_using_bionic_weapon(), NEXT, null_item_reference(), rules, SKIP, item::type, use_guns, use_silent, Character::visit_items(), Character::weapon, and Character::weapon_value().

Referenced by npc_attack_throw::evaluate(), and wield_better_weapon().

◆ evaluate_character()

float npc::evaluate_character ( const Character candidate,
bool  my_gun,
bool  enemy = true 
)

Definition at line 484 of file npcmove.cpp.

485 {
486  float threat = 0.0f;
487  bool candidate_gun = candidate.get_wielded_item() && candidate.get_wielded_item()->is_gun();
488  const item &candidate_weap = candidate.get_wielded_item() ? *candidate.get_wielded_item() :
490  double candidate_weap_val = candidate.weapon_value( candidate_weap );
491  float candidate_health = candidate.hp_percentage() / 100.0f;
492  float armour = estimate_armour( candidate );
493  float speed = std::max( 0.25f, candidate.get_speed() / 100.0f );
494  bool is_fleeing = candidate.has_effect( effect_npc_run_away );
495  int perception_inverted = std::max( ( 20 - get_per() ), 0 );
496  if( has_effect( effect_bleed ) ) {
497  int bleed_intensity = 0;
498  for( const bodypart_id &bp : candidate.get_all_body_parts() ) {
499  const effect &bleediness = candidate.get_effect( effect_bleed, bp );
500  if( !bleediness.is_null() && bleediness.get_intensity() > perception_inverted / 2 ) {
501  // unlike in evaluate self, NPCs can't notice bleeding in others unless it's pretty high.
502  bleed_intensity += bleediness.get_intensity();
503  }
504  }
505  candidate_health *= std::max( 1.0f - bleed_intensity / 10.0f, 0.25f );
507  "<color_red>%s is bleeeeeeding…</color>, intensity %i", candidate.disp_name(), bleed_intensity );
508  }
509  if( !enemy ) {
510  if( candidate_gun || ( is_player_ally() && candidate.is_avatar() ) ) {
511  // later we should evaluate if the NPC trusts the player enough to stick to them so reliably
512  int dist = rl_dist( pos(), candidate.pos() );
513  if( dist > mem_combat.formation_distance ) {
515  }
516  }
517  }
518 
519  if( !my_gun ) {
520  speed = std::max( speed, 0.5f );
521  };
522 
523  threat += my_gun && enemy ? candidate.get_dodge() / 2.0f : candidate.get_dodge();
524  threat += armour;
526  "<color_cyan>evaluate_character </color><color_light_gray>%s assesses %s defense value as %1.2f.</color>",
527  name, candidate.disp_name( true ), threat );
528 
529  if( enemy && candidate_gun && !my_gun ) {
531  "<color_light_gray>%s has a gun and %s doesn't; %s adjusts threat accordingly.</color>",
532  candidate.disp_name(), name, name );
533  candidate_weap_val *= 1.5f;
534  }
535  threat += candidate_weap_val;
537  "<color_light_gray>%s assesses %s weapon value as %1.2f.</color>",
538  name, candidate.disp_name( true ), candidate_weap_val );
540  "<color_light_gray>%s assesses</color> %s threat: %1.2f <color_light_gray>before personality and situation changes.</color>",
541  name,
542  candidate.disp_name( true ), threat );
543  if( enemy ) {
544  threat -= static_cast<float>( personality.aggression );
545  } else {
546  threat += static_cast<float>( personality.bravery );
547  }
548 
549  threat *= speed;
551  "<color_light_gray>%s scales %s threat by %1.0f%% based on speed.</color>",
552  name, candidate.disp_name( true ), speed * 100.0f );
553  threat *= candidate_health;
555  "<color_light_gray>%s scales %s threat by %1.0f%% based on remaining health.</color>", name,
556  candidate.disp_name( true ), candidate_health * 100.0f );
557 
558  if( is_fleeing ) {
559  threat *= 0.5f;
561  "<color_light_gray>%s scales %s threat by 50%% because they're running away.</color>", name,
562  candidate.disp_name( true ) );
563  }
565  "<color_light_gray>%s sets </color>%s threat: %1.2f <color_light_gray>before perception randomization.</color>",
566  name,
567  candidate.disp_name( true ), threat );
568  // the math for perception fuzz is this way to make it more human readable because I kept making silly errors.
569  // I hope this helps you too. If not, well, sorry bud.
570  // Anyway the higher your perception gets the more accurate and predictable your rating is.
571  // this will become more valuable the more skilled we make NPCs at assessing enemies.
572  // At time of writing they're bad at it so this is mostly just me patting myself on the back for adding a cool looking feature.
573  int perception_factor = rng( -10, 10 ) * perception_inverted;
574 
576  "<color_light_gray>%s randomizes %s threat by %1.1f%% based on perception factor %i.</color> Final threat %1.2f",
577  name, candidate.disp_name( true ), threat * perception_factor / 1000.0f, perception_factor,
578  threat + threat * perception_factor / 1000.0f );
579  threat += threat * perception_factor / 1000.0f;
580 
581  add_msg_debug( debugmode::DF_NPC, "<color_light_gray>%s assesses </color>%s final threat: %1.2f",
582  name,
583  candidate.disp_name( true ),
584  threat );
585  return std::min( threat, NPC_CHARACTER_DANGER_MAX );
586 }
float get_dodge() const override
Returns Creature::get_dodge() modified by any Character effects.
Definition: melee.cpp:1208
bool is_null() const
Returns true if the effect is the result of effect(), ie.
Definition: effect.cpp:767
float estimate_armour(const Character &candidate) const
Definition: npcmove.cpp:649
constexpr float NPC_CHARACTER_DANGER_MAX
Definition: npc.h:64
int8_t aggression
Definition: npc.h:217

References add_msg_debug, npc_personality::aggression, bp, npc_personality::bravery, debugmode::DF_NPC, debugmode::DF_NPC_COMBATAI, Character::disp_name(), effect_bleed, effect_npc_run_away, npc_combat_memory_cache::engagement_distance, estimate_armour(), npc_combat_memory_cache::formation_distance, Creature::get_all_body_parts(), Character::get_dodge(), Creature::get_effect(), effect::get_intensity(), Character::get_per(), Character::get_speed(), Character::get_wielded_item(), Creature::has_effect(), Character::hp_percentage(), Creature::is_avatar(), item::is_gun(), effect::is_null(), is_player_ally(), max(), mem_combat, min(), Character::name, NPC_CHARACTER_DANGER_MAX, null_item_reference(), personality, Creature::pos(), rl_dist(), rng(), speed, and Character::weapon_value().

Referenced by assess_danger().

◆ evaluate_monster()

float npc::evaluate_monster ( const monster target,
int  dist 
) const

rates how dangerous a target is

Definition at line 467 of file npcmove.cpp.

468 {
469  float speed = target.speed_rating();
470  float scaled_distance = std::max( 1.0f, dist * dist / ( speed * 250.0f ) );
471  float hp_percent = static_cast<float>( target.get_hp() ) / target.get_hp_max();
472  float diff = std::max( static_cast<float>( target.type->difficulty ), NPC_DANGER_VERY_LOW );
474  "<color_yellow>evaluate_monster </color><color_dark_gray>%s thinks %s threat level is <color_light_gray>%1.2f</color><color_dark_gray> before considering situation. Speed rating: %1.2f; dist: %i; scaled_distance: %1.0f; HP: %1.0f%%</color>",
475  name, target.type->nname(), diff, speed, dist, scaled_distance, hp_percent * 100 );
476  // Note that the danger can pass below "very low" if the monster is weak and far away.
477  diff *= ( hp_percent * 0.5f + 0.5f ) / scaled_distance;
479  "<color_light_gray>%s puts final %s threat level at </color>%1.2f<color_light_gray> after counting speed, distance, hp</color>",
480  name, target.type->nname(), diff );
481  return std::min( diff, NPC_MONSTER_DANGER_MAX );
482 }
int get_hp(const bodypart_id &) const override
Definition: monster.cpp:3743
int get_hp_max(const bodypart_id &) const override
Definition: monster.cpp:3733
const mtype * type
Definition: monster.h:550
float speed_rating() const override
Returns an approximate number of tiles this creature can travel per turn.
Definition: monster.cpp:3662
int difficulty
Definition: mtype.h:409
std::string nname(unsigned int quantity=1) const
Definition: mtype.cpp:330

References add_msg_debug, debugmode::DF_NPC_COMBATAI, mtype::difficulty, monster::get_hp(), monster::get_hp_max(), max(), min(), Character::name, mtype::nname(), NPC_DANGER_VERY_LOW, NPC_MONSTER_DANGER_MAX, speed, monster::speed_rating(), and monster::type.

Referenced by assess_danger().

◆ evaluate_self()

float npc::evaluate_self ( bool  my_gun)

Definition at line 588 of file npcmove.cpp.

589 {
590  float threat = 0.0f;
591  const double &my_weap_val = ai_cache.my_weapon_value;
592  // the worse pain the NPC is in, the more likely they are to overestimate the severity of their injuries.
593  // the more perceptive they are, the more they're able to see how bad it really is.
594  // Randomize it such that it becomes more swingy as their emotions and pain grow higher.
595  float pain_factor = rng( 0.0f,
596  static_cast<float>( get_pain() ) / static_cast<float>( get_per() ) );
597  mem_combat.my_health = ( hp_percentage() - pain_factor ) / 100.0f;
598  float armour = estimate_armour( dynamic_cast<const Character &>( *this ) );
599  float speed = std::max( 0.5f, get_speed() / 100.0f );
600  if( my_gun ) {
601  speed = std::max( speed, 0.75f );
602  }
603  if( has_effect( effect_bleed ) ) {
604  int bleed_intensity = 0;
605  for( const bodypart_id &bp : get_all_body_parts() ) {
606  const effect &bleediness = get_effect( effect_bleed, bp );
607  if( !bleediness.is_null() ) {
608  bleed_intensity += bleediness.get_intensity();
609  }
610  }
611  mem_combat.my_health *= std::max( 1.0f - bleed_intensity / 10.0f, 0.25f );
613  "<color_red>%s is bleeeeeeding…</color>, intensity %i", name, bleed_intensity );
614  if( mem_combat.my_health < 0.25f ) {
615  mem_combat.panic += 1;
616  }
617  }
618 
619 
620  threat += get_dodge();
621  threat += armour;
623  "<color_light_green>evaluate_self </color><color_light_gray>%s assesses own defense value as %1.2f.</color>",
624  name, threat );
625 
626  threat += my_weap_val;
628  "<color_light_gray>%s assesses own weapon value as %1.2f.",
629  name, my_weap_val );
630 
631  threat += static_cast<float>( personality.bravery + personality.aggression );
633  "<color_light_gray>%s updates own threat by %i based on personality.",
635 
636  threat *= speed;
638  "<color_light_gray>%s scales own threat by %1.0f%% based on speed.",
639  name, speed * 100.0f );
640  threat *= mem_combat.my_health;
642  "<color_light_gray>%s scales own threat by %1.0f%% based on remaining health (reduced by %1.2f%% due to pain).</color> Final value: %1.2f",
643  name,
644  mem_combat.my_health * 100.0f, pain_factor, threat );
645  add_msg_debug( debugmode::DF_NPC, "%s assesses own threat as %1.2f", name, threat );
646  return std::min( threat, NPC_CHARACTER_DANGER_MAX );
647 }
double my_weapon_value
Definition: npc.h:579

References add_msg_debug, npc_personality::aggression, ai_cache, bp, npc_personality::bravery, debugmode::DF_NPC, debugmode::DF_NPC_COMBATAI, effect_bleed, estimate_armour(), Creature::get_all_body_parts(), Character::get_dodge(), Creature::get_effect(), effect::get_intensity(), Creature::get_pain(), Character::get_per(), Character::get_speed(), Creature::has_effect(), Character::hp_percentage(), effect::is_null(), max(), mem_combat, min(), npc_combat_memory_cache::my_health, npc_short_term_cache::my_weapon_value, Character::name, NPC_CHARACTER_DANGER_MAX, npc_combat_memory_cache::panic, personality, rng(), and speed.

Referenced by assess_danger().

◆ evaluate_sleep_spot()

int npc::evaluate_sleep_spot ( tripoint_bub_ms  p)

Definition at line 2043 of file npcmove.cpp.

2044 {
2045  // Base evaluation is based on ability to actually fall sleep there
2046  int sleep_eval = sleep_spot( p );
2047  // Only evaluate further if the possible bed isn't already considered very comfortable.
2048  // This opt-out is necessary to allow mutant NPCs to find desired non-bed sleeping spaces
2049  if( sleep_eval < static_cast<int>( comfort_level::very_comfortable ) - 1 ) {
2050  const units::temperature_delta ideal_bed_value = 2_C_delta;
2051  const units::temperature_delta sleep_spot_value = floor_bedding_warmth( p.raw() );
2052  if( sleep_spot_value < ideal_bed_value ) {
2053  double bed_similarity = sleep_spot_value / ideal_bed_value;
2054  // bed_similarity^2, exponentially diminishing the value of non-bed sleeping spots the more not-bed-like they are
2055  sleep_eval *= pow( bed_similarity, 2 );
2056  }
2057  }
2058  return sleep_eval;
2059 }
int sleep_spot(const tripoint_bub_ms &p) const
Rate point's ability to serve as a bed.
static units::temperature_delta floor_bedding_warmth(const tripoint &pos)
Warmth from terrain, furniture, vehicle furniture and traps.
Definition: character.cpp:9216

References Character::floor_bedding_warmth(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), Character::sleep_spot(), and Character::very_comfortable.

Referenced by execute_action().

◆ evaluate_weapon()

double npc::evaluate_weapon ( item maybe_weapon,
bool  can_use_gun,
bool  use_silent 
) const

Definition at line 4045 of file npcmove.cpp.

4046 {
4047  bool allowed = can_use_gun && it.is_gun() && ( !use_silent || it.is_silent() );
4048  // According to unmodified evaluation score, NPCs almost always prioritize wielding guns if they have one.
4049  // This is relatively reasonable, as players can issue commands to NPCs when we do not want them to use ranged weapons.
4050  // Conversely, we cannot directly issue commands when we want NPCs to prioritize ranged weapons.
4051  // Note that the scoring method here is different from the 'weapon_value' used elsewhere.
4052  double val_gun = allowed ? gun_value( it, it.shots_remaining( this ) ) : 0;
4054  "%s %s valued at <color_light_cyan>%1.2f as a ranged weapon to wield</color>.",
4055  disp_name( true ), it.type->get_id().str(), val_gun );
4056  double val_melee = melee_value( it );
4058  "%s %s valued at <color_light_cyan>%1.2f as a melee weapon to wield</color>.", disp_name( true ),
4059  it.type->get_id().str(), val_melee );
4060  double val = std::max( val_gun, val_melee );
4061  return val;
4062 }
double gun_value(const item &weap, int ammo=10) const
Definition: ranged.cpp:2339

References add_msg_debug, debugmode::DF_NPC_ITEMAI, Character::disp_name(), itype::get_id(), Character::gun_value(), item::is_gun(), item::is_silent(), max(), Character::melee_value(), item::shots_remaining(), string_id< T >::str(), item::type, and use_silent.

Referenced by evaluate_best_weapon(), and wield_better_weapon().

◆ execute_action()

void npc::execute_action ( npc_action  action)

Definition at line 1565 of file npcmove.cpp.

1566 {
1567  int oldmoves = moves;
1568  tripoint tar = pos();
1569  Creature *cur = current_target();
1570  if( action == npc_flee ) {
1571  tar = good_escape_direction( false );
1572  } else if( cur != nullptr ) {
1573  tar = cur->pos();
1574  }
1575  /*
1576  debugmsg("%s ran execute_action() with target = %d! Action %s",
1577  name, target, npc_action_name(action));
1578  */
1579 
1580  Character &player_character = get_player_character();
1581  map &here = get_map();
1582  switch( action ) {
1583  case npc_do_attack:
1585  ai_cache.current_attack.reset();
1587  break;
1588  case npc_pause:
1589  move_pause();
1590  break;
1591  case npc_worker_downtime:
1592  worker_downtime();
1593  break;
1594  case npc_reload: {
1595  if( !get_wielded_item() ) {
1596  debugmsg( "NPC tried to reload without weapon" );
1597  }
1599  }
1600  break;
1601 
1602  case npc_investigate_sound: {
1603  tripoint cur_pos = pos();
1605  move_to_next();
1606  if( pos() == cur_pos ) {
1607  ai_cache.stuck += 1;
1608  }
1609  }
1610  break;
1611 
1612  case npc_return_to_guard_pos: {
1613  const tripoint local_guard_pos = here.getlocal( *ai_cache.guard_pos );
1614  update_path( local_guard_pos );
1615  if( pos() == local_guard_pos || path.empty() ) {
1616  move_pause();
1617  ai_cache.guard_pos = std::nullopt;
1618  path.clear();
1619  } else {
1620  move_to_next();
1621  }
1622  }
1623  break;
1624 
1625  case npc_sleep: {
1626  // TODO: Allow stims when not too tired
1627  // Find a nice spot to sleep
1628  tripoint_bub_ms best_spot = pos_bub();
1629  int best_sleepy = evaluate_sleep_spot( best_spot );
1631  if( !could_move_onto( p ) || !g->is_empty( p ) ) {
1632  continue;
1633  }
1634 
1635  // For non-mutants, very_comfortable-1 is the expected value of an ideal normal bed.
1636  if( best_sleepy < static_cast<int>( comfort_level::very_comfortable ) - 1 ) {
1637  const int sleepy = evaluate_sleep_spot( p );
1638  if( sleepy > best_sleepy ) {
1639  best_sleepy = sleepy;
1640  best_spot = p;
1641  }
1642  }
1643  }
1644  if( is_walking_with() ) {
1645  complain_about( "napping", 30_minutes, chat_snippets().snip_warn_sleep.translated() );
1646  }
1647  update_path( best_spot );
1648  // TODO: Handle empty path better
1649  if( best_spot == pos_bub() || path.empty() ) {
1650  move_pause();
1651  if( !has_effect( effect_lying_down ) ) {
1653  add_effect( effect_lying_down, 30_minutes, false, 1 );
1654  if( !player_character.in_sleep_state() ) {
1655  add_msg_if_player_sees( *this, _( "%s lies down to sleep." ), get_name() );
1656  }
1657  }
1658  } else {
1659  move_to_next();
1660  }
1661  }
1662  break;
1663 
1664  case npc_pickup:
1665  pick_up_item();
1666  break;
1667 
1668  case npc_heal:
1669  heal_self();
1670  break;
1671 
1672  case npc_use_painkiller:
1673  use_painkiller();
1674  break;
1675 
1676  case npc_drop_items:
1677  /* NPCs can't choose this action anymore, but at least it works */
1679  /* drop_items is still broken
1680  * drop_items( weight_carried() - weight_capacity(),
1681  * volume_carried() - volume_capacity() );
1682  */
1683  move_pause();
1684  break;
1685 
1686  case npc_flee:
1687  if( path.empty() ) {
1688  move_to( tar );
1689  } else {
1690  move_to_next();
1691  }
1692  break;
1693 
1694  case npc_reach_attack:
1695  if( can_use_offensive_cbm() ) {
1697  }
1698  reach_attack( tar );
1699  break;
1700  case npc_melee:
1701  update_path( tar );
1702  if( path.size() > 1 ) {
1703  move_to_next();
1704  } else if( path.size() == 1 ) {
1705  if( cur != nullptr ) {
1706  if( can_use_offensive_cbm() ) {
1708  }
1709  melee_attack( *cur, true );
1710  }
1711  } else {
1712  look_for_player( player_character );
1713  }
1714  break;
1715 
1716  case npc_aim:
1717  aim( Target_attributes( pos(), tar ) );
1718  break;
1719 
1720  case npc_shoot: {
1721  if( !get_wielded_item() ) {
1722  debugmsg( "NPC tried to shoot without weapon" );
1723  }
1725  if( !mode ) {
1726  debugmsg( "NPC tried to shoot without valid mode" );
1727  break;
1728  }
1729  aim( Target_attributes( pos(), tar ) );
1730  if( is_hallucination() ) {
1731  pretend_fire( this, mode.qty, *mode );
1732  } else {
1733  fire_gun( tar, mode.qty, *mode );
1734  // "discard" the fake bio weapon after shooting it
1735  if( is_using_bionic_weapon() ) {
1737  }
1738  }
1739  break;
1740  }
1741 
1742  case npc_look_for_player:
1744  sees( here.getlocal( *last_player_seen_pos ) ) ) {
1746  move_to_next();
1747  } else {
1748  look_for_player( player_character );
1749  }
1750  break;
1751 
1752  case npc_heal_player: {
1753  Character *patient = dynamic_cast<Character *>( current_ally() );
1754  if( patient ) {
1755  update_path( patient->pos() );
1756  if( path.size() == 1 ) { // We're adjacent to u, and thus can heal u
1757  heal_player( *patient );
1758  } else if( !path.empty() ) {
1759  std::string talktag = chat_snippets().snip_heal_player.translated();
1760  parse_tags( talktag, get_player_character(), *this );
1761  say( string_format( talktag, patient->disp_name() ) );
1762  move_to_next();
1763  } else {
1764  move_pause();
1765  }
1766  }
1767  break;
1768  }
1769  case npc_follow_player:
1770  update_path( player_character.pos() );
1771  if( path.empty() ||
1772  ( static_cast<int>( path.size() ) <= follow_distance() &&
1773  player_character.posz() == posz() ) ) {
1774  // We're close enough to u.
1775  move_pause();
1776  } else {
1777  move_to_next();
1778  }
1779  // TODO: Make it only happen when it's safe
1780  complain();
1781  break;
1782 
1783  case npc_follow_embarked: {
1784  const optional_vpart_position vp = here.veh_at( player_character.pos() );
1785  if( !vp ) {
1786  debugmsg( "Following an embarked player with no vehicle at their location?" );
1787  // TODO: change to wait? - for now pause
1788  move_pause();
1789  break;
1790  }
1791  vehicle *const veh = &vp->vehicle();
1792 
1793  // Try to find the last destination
1794  // This is mount point, not actual position
1795  point last_dest( INT_MIN, INT_MIN );
1796  if( !path.empty() && veh_pointer_or_null( here.veh_at( path[path.size() - 1] ) ) == veh ) {
1797  last_dest = vp->mount();
1798  }
1799 
1800  // Prioritize last found path, then seats
1801  // Don't change spots if ours is nice
1802  int my_spot = -1;
1803  std::vector<std::pair<int, int> > seats;
1804  for( const vpart_reference &vp : veh->get_avail_parts( VPFLAG_BOARDABLE ) ) {
1805  const Character *passenger = veh->get_passenger( vp.part_index() );
1806  if( passenger != this && passenger != nullptr ) {
1807  continue;
1808  }
1809  // A seat is available if we can move there and it's either unassigned or assigned to us
1810  auto available_seat = [&]( const vehicle_part & pt ) {
1811  tripoint target = veh->global_part_pos3( pt );
1812  if( !pt.is_seat() ) {
1813  return false;
1814  }
1815  if( !could_move_onto( target ) ) {
1816  return false;
1817  }
1818  const npc *who = pt.crew();
1819  return !who || who->getID() == getID();
1820  };
1821 
1822  const vehicle_part &pt = vp.part();
1823 
1824  int priority = 0;
1825 
1826  if( vp.mount() == last_dest ) {
1827  // Shares mount point with last known path
1828  // We probably wanted to go there in the last turn
1829  priority = 4;
1830 
1831  } else if( available_seat( pt ) ) {
1832  // Assuming player "owns" a sensible vehicle seats should be in good spots to occupy
1833  // Prefer our assigned seat if we have one
1834  const npc *who = pt.crew();
1835  priority = who && who->getID() == getID() ? 3 : 2;
1836 
1837  } else if( vp.is_inside() ) {
1838  priority = 1;
1839  }
1840 
1841  if( passenger == this ) {
1842  my_spot = priority;
1843  }
1844 
1845  seats.emplace_back( priority, static_cast<int>( vp.part_index() ) );
1846  }
1847 
1848  if( my_spot >= 3 ) {
1849  // We won't get any better, so don't try
1850  move_pause();
1851  break;
1852  }
1853 
1854  std::sort( seats.begin(), seats.end(),
1855  []( const std::pair<int, int> &l, const std::pair<int, int> &r ) {
1856  return l.first > r.first;
1857  } );
1858 
1859  if( seats.empty() ) {
1860  // TODO: be angry at player, switch to wait or leave - for now pause
1861  move_pause();
1862  break;
1863  }
1864 
1865  // Only check few best seats - pathfinding can get expensive
1866  const size_t try_max = std::min<size_t>( 4, seats.size() );
1867  for( size_t i = 0; i < try_max; i++ ) {
1868  if( seats[i].first <= my_spot ) {
1869  // We have a nicer spot than this
1870  // Note: this will make NPCs steal player's seat...
1871  break;
1872  }
1873 
1874  const int cur_part = seats[i].second;
1875 
1876  tripoint pp = veh->global_part_pos3( cur_part );
1877  update_path( pp, true );
1878  if( !path.empty() ) {
1879  // All is fine
1880  move_to_next();
1881  break;
1882  }
1883  }
1884 
1885  // TODO: Check the rest
1886  move_pause();
1887  }
1888 
1889  break;
1890  case npc_talk_to_player:
1891  get_avatar().talk_to( get_talker_for( this ) );
1892  set_moves( 0 );
1893  break;
1894 
1895  case npc_mug_player:
1896  mug_player( player_character );
1897  break;
1898 
1899  case npc_goto_to_this_pos: {
1900  update_path( get_map().getlocal( *goto_to_this_pos ) );
1901  move_to_next();
1902 
1903  if( get_location() == *goto_to_this_pos ) {
1904  goto_to_this_pos = std::nullopt;
1905  }
1906  break;
1907  }
1908 
1909  case npc_goto_destination:
1911  break;
1912 
1915  break;
1916 
1917  case npc_escape_explosion:
1918  escape_explosion();
1919  break;
1920 
1921  case npc_player_activity:
1923  break;
1924 
1925  case npc_undecided:
1926  complain();
1927  move_pause();
1928  break;
1929 
1930  case npc_noop:
1931  add_msg_debug( debugmode::DF_NPC, "%s skips turn (noop)", disp_name() );
1932  return;
1933 
1934  default:
1935  debugmsg( "Unknown NPC action (%d)", action );
1936  }
1937 
1938  if( oldmoves == moves ) {
1939  add_msg_debug( debugmode::DF_NPC, "NPC didn't use its moves. Action %s (%d).",
1941  }
1942 }
std::unique_ptr< talker > get_talker_for(avatar &me)
Definition: avatar.cpp:1795
avatar & get_avatar()
Definition: game.cpp:13817
bool melee_attack(Creature &t, bool allow_special, const matec_id &force_technique, bool allow_unarmed=true, int forced_movecost=-1)
Sets up a melee attack and handles melee attack function calls.
Definition: melee.cpp:563
void reach_attack(const tripoint &p, int forced_movecost=-1)
Handles reach melee attacks.
Definition: melee.cpp:1012
int fire_gun(const tripoint &target, int shots=1)
Fires a gun or auxiliary gunmod (ignoring any current mode)
Definition: ranged.cpp:857
void drop_invalid_inventory()
tripoint_bub_ms pos_bub() const
Definition: creature.cpp:183
void talk_to(std::unique_ptr< talker > talk_with, bool radio_contact=false, bool is_computer=false, bool is_not_conversation=false)
Definition: npctalk.cpp:1358
int qty
burst size for is_gun() firearms, or melee range for is_melee() weapons
Definition: gun_mode.h:21
gun_mode gun_current_mode() const
Get the current mode for this gun (or an invalid mode if item is not a gun)
Definition: item.cpp:11420
tripoint getlocal(const tripoint &p) const
Inverse of getabs.
Definition: map.cpp:9635
optional_vpart_position veh_at(const tripoint &p) const
Checks if tile is occupied by vehicle and by which part.
Definition: map.cpp:1316
tripoint target() const
Definition: npc_attack.h:30
std::optional< tripoint_abs_ms > goto_to_this_pos
Definition: npc.h:1363
bool complain()
Definition: npcmove.cpp:5242
const Creature * current_ally() const
Definition: npcmove.cpp:5110
void escape_explosion()
Definition: npcmove.cpp:3211
void heal_player(Character &patient)
Definition: npcmove.cpp:4328
void worker_downtime()
Definition: npcmove.cpp:3289
bool saw_player_recently() const
Definition: npcmove.cpp:4784
void aim(const Target_attributes &target_attributes)
Definition: npcmove.cpp:2798
void go_to_omt_destination()
Definition: npcmove.cpp:4945
int evaluate_sleep_spot(tripoint_bub_ms p)
Definition: npcmove.cpp:2043
bool do_player_activity()
perform a player activity, returning true if it took up the turn
Definition: npcmove.cpp:3989
void mug_player(Character &mark)
Definition: npcmove.cpp:4660
void use_painkiller()
Definition: npcmove.cpp:4425
void look_for_player(const Character &sought)
Definition: npcmove.cpp:4743
void pretend_fire(npc *source, int shots, item &gun)
Definition: ranged.cpp:835
void heal_self()
Definition: npcmove.cpp:4374
tripoint good_escape_direction(bool include_pos=true)
Definition: npcmove.cpp:260
void pick_up_item()
Definition: npcmove.cpp:3655
Simple wrapper to forward functions that may return a std::optional to vpart_position.
A vehicle as a whole with all its components.
Definition: vehicle.h:802
vehicle_part_with_feature_range< std::string > get_avail_parts(std::string feature) const
Yields a range of parts of this vehicle that each have the given feature and are available: not broke...
Definition: vehicle.cpp:3007
Character * get_passenger(int you) const
Definition: vehicle.cpp:3403
tripoint global_part_pos3(const int &index) const
Get the coordinates of the studied part of the vehicle.
Definition: vehicle.cpp:3442
This is a wrapper over a vehicle pointer and a reference to a part of it.
constexpr int ACTIVITY_SEARCH_DISTANCE
Definition: clzones.h:37
@ npc_worker_downtime
Definition: npcmove.cpp:186
@ npc_investigate_sound
Definition: npcmove.cpp:183
@ npc_melee
Definition: npcmove.cpp:172
@ npc_goto_to_this_pos
Definition: npcmove.cpp:175
@ npc_reach_attack
Definition: npcmove.cpp:180
@ npc_shoot
Definition: npcmove.cpp:172
@ npc_drop_items
Definition: npcmove.cpp:171
@ npc_look_for_player
Definition: npcmove.cpp:173
@ npc_return_to_guard_pos
Definition: npcmove.cpp:184
@ npc_avoid_friendly_fire
Definition: npcmove.cpp:177
@ npc_escape_explosion
Definition: npcmove.cpp:178
@ npc_pickup
Definition: npcmove.cpp:170
@ npc_aim
Definition: npcmove.cpp:182
@ npc_do_attack
Definition: npcmove.cpp:181
@ npc_follow_embarked
Definition: npcmove.cpp:173
static std::string npc_action_name(npc_action action)
Definition: npcmove.cpp:5021
static const bionic_id bio_soporific("bio_soporific")
static const efftype_id effect_lying_down("lying_down")
tripoint s_abs_pos
Definition: npc.h:574
std::optional< tripoint_abs_ms > guard_pos
Definition: npc.h:578
Definition: point.h:20
Structure, describing vehicle part (i.e., wheel, seat)
Definition: vehicle.h:254
npc * crew() const
Get NPC currently assigned to this part (seat, turret etc)?
@ VPFLAG_BOARDABLE
Definition: veh_type.h:67
vehicle * veh_pointer_or_null(const optional_vpart_position &p)

References _, action, activate_bionic_by_id(), ACTIVITY_SEARCH_DISTANCE, Creature::add_effect(), add_msg_debug, add_msg_if_player_sees(), ai_cache, aim(), avoid_friendly_fire(), bio_hydraulics, bio_soporific, can_use_offensive_cbm(), chat_snippets(), closest_points_first(), complain(), complain_about(), could_move_onto(), vehicle_part::crew(), current_ally(), npc_short_term_cache::current_attack, npc_short_term_cache::current_attack_evaluation, current_target(), debugmsg, debugmode::DF_NPC, discharge_cbm_weapon(), Character::disp_name(), do_player_activity(), do_reload(), Character::drop_invalid_inventory(), effect_lying_down, escape_explosion(), evaluate_sleep_spot(), Character::fire_gun(), follow_distance(), g, vehicle::get_avail_parts(), get_avatar(), Creature::get_location(), get_map(), Character::get_name(), vehicle::get_passenger(), get_player_character(), get_talker_for(), Character::get_wielded_item(), Character::getID(), map::getlocal(), vehicle::global_part_pos3(), go_to_omt_destination(), good_escape_direction(), goto_to_this_pos, npc_short_term_cache::guard_pos, item::gun_current_mode(), Creature::has_effect(), heal_player(), heal_self(), Character::in_sleep_state(), is_hallucination(), Character::is_using_bionic_weapon(), is_walking_with(), last_player_seen_pos, look_for_player(), Character::melee_attack(), move_pause(), move_to(), move_to_next(), Creature::moves, mug_player(), npc_action_name(), npc_aim, npc_avoid_friendly_fire, npc_do_attack, npc_drop_items, npc_escape_explosion, npc_flee, npc_follow_embarked, npc_follow_player, npc_goto_destination, npc_goto_to_this_pos, npc_heal, npc_heal_player, npc_investigate_sound, npc_look_for_player, npc_melee, npc_mug_player, npc_noop, npc_pause, npc_pickup, npc_player_activity, npc_reach_attack, npc_reload, npc_return_to_guard_pos, npc_shoot, npc_sleep, npc_talk_to_player, npc_undecided, npc_use_painkiller, npc_worker_downtime, parse_tags(), path, pick_up_item(), Creature::pos(), Creature::pos_bub(), Creature::posz(), pretend_fire(), gun_mode::qty, Character::reach_attack(), npc_short_term_cache::s_abs_pos, saw_player_recently(), say(), Character::sees(), Creature::set_moves(), dialogue_chatbin_snippets::snip_heal_player, string_format(), npc_short_term_cache::stuck, avatar::talk_to(), npc_attack_rating::target(), translation::translated(), update_path(), use_painkiller(), map::veh_at(), veh_pointer_or_null(), Character::very_comfortable, VPFLAG_BOARDABLE, and worker_downtime().

Referenced by avoid_friendly_fire(), and move().

◆ export_to()

void npc::export_to ( const cata_path path) const

Definition at line 1802 of file savegame.cpp.

1803 {
1804  write_to_file( path, [&]( std::ostream & fout ) {
1805  fout << "# version " << savegame_version << std::endl;
1806  JsonOut jsout( fout );
1807  serialize( jsout );
1808  } );
1809 }
void write_to_file(const std::string &path, const std::function< void(std::ostream &)> &writer)
Definition: json.h:736
void serialize(JsonOut &json) const override
const int savegame_version
Definition: savegame.cpp:71

References path, savegame_version, serialize(), and write_to_file().

Referenced by debug_menu::debug(), and avatar::export_as_npc().

◆ extended_description()

std::string npc::extended_description ( ) const
overridevirtual

Reimplemented from Character.

Definition at line 3372 of file npc.cpp.

3373 {
3374  std::string ss;
3375  // For some reason setting it using str or constructor doesn't work
3377 
3378  ss += "\n--\n";
3379  if( attitude == NPCATT_KILL ) {
3380  ss += _( "Is trying to kill you." );
3381  } else if( attitude == NPCATT_FLEE || attitude == NPCATT_FLEE_TEMP ) {
3382  ss += _( "Is trying to flee from you." );
3383  } else if( is_player_ally() ) {
3384  ss += _( "Is your friend." );
3385  } else if( is_following() ) {
3386  ss += _( "Is following you." );
3387  } else if( is_leader() ) {
3388  ss += _( "Is guiding you." );
3389  } else if( guaranteed_hostile() ) {
3390  ss += _( "Will try to kill you or flee from you if you reveal yourself." );
3391  } else {
3392  ss += _( "Is neutral." );
3393  }
3394 
3395  if( hit_by_player ) {
3396  ss += "--\n";
3397  ss += _( "Is still innocent and killing them will be considered murder." );
3398  // TODO: "But you don't care because you're an edgy psycho"
3399  }
3400 
3401  return replace_colors( ss );
3402 }
std::string extended_description() const override
Definition: character.cpp:6214
bool is_leader() const
Definition: npc.cpp:2332
bool is_following() const
Definition: npc.cpp:2327
std::string replace_colors(std::string text)
Definition: output.cpp:998

References _, attitude, Character::extended_description(), guaranteed_hostile(), hit_by_player, is_following(), is_leader(), is_player_ally(), NPCATT_FLEE, NPCATT_FLEE_TEMP, NPCATT_KILL, and replace_colors().

◆ faction_display()

int npc::faction_display ( const catacurses::window fac_w,
int  width 
) const

Definition at line 615 of file faction.cpp.

616 {
617  int retval = 0;
618  int y = 2;
619  const nc_color col = c_white;
620  Character &player_character = get_player_character();
621  const tripoint_abs_omt player_abspos = player_character.global_omt_location();
622 
623  //get NPC followers, status, direction, location, needs, weapon, etc.
624  mvwprintz( fac_w, point( width, ++y ), c_light_gray, _( "Press enter to talk to this follower " ) );
625  std::string mission_string;
626  if( has_companion_mission() ) {
627  std::string dest_string;
628  std::optional<tripoint_abs_omt> dest = get_mission_destination();
629  if( dest ) {
630  basecamp *dest_camp;
631  std::optional<basecamp *> temp_camp = overmap_buffer.find_camp( dest->xy() );
632  if( temp_camp ) {
633  dest_camp = *temp_camp;
634  dest_string = _( "traveling to: " ) + dest_camp->camp_name();
635  } else {
636  dest_string = string_format( _( "traveling to: %s" ), dest->to_string() );
637  }
638  mission_string = _( "Current Mission: " ) + dest_string;
639  } else {
641  mission_string = _( "Current Mission: " ) + action_of( c_mission.miss_id.id );
642  }
643  fold_and_print( fac_w, point( width, ++y ), getmaxx( fac_w ) - width - 2, col, mission_string );
644 
645  // Determine remaining time in mission, and display it
646  std::string mission_eta;
648  mission_eta = _( "JOB COMPLETED" );
649  } else {
650  mission_eta = _( "ETA: " ) + to_string( companion_mission_time_ret - calendar::turn );
651  }
652  fold_and_print( fac_w, point( width, ++y ), getmaxx( fac_w ) - width - 2, col, mission_eta );
653  }
654 
655  tripoint_abs_omt guy_abspos = global_omt_location();
656  basecamp *temp_camp = nullptr;
657  if( assigned_camp ) {
658  std::optional<basecamp *> bcp = overmap_buffer.find_camp( ( *assigned_camp ).xy() );
659  if( bcp ) {
660  temp_camp = *bcp;
661  }
662  }
663  const bool is_stationed = assigned_camp && temp_camp;
664  std::string direction = direction_name( direction_from( player_abspos, guy_abspos ) );
665  if( direction != "center" ) {
666  mvwprintz( fac_w, point( width, ++y ), col, _( "Direction: to the " ) + direction );
667  } else {
668  mvwprintz( fac_w, point( width, ++y ), col, _( "Direction: Nearby" ) );
669  }
670  if( is_stationed ) {
671  mvwprintz( fac_w, point( width, ++y ), col, _( "Location: %s, at camp: %s" ),
672  guy_abspos.to_string(), temp_camp->camp_name() );
673  } else {
674  mvwprintz( fac_w, point( width, ++y ), col, _( "Location: %s" ), guy_abspos.to_string() );
675  }
676  std::string can_see;
677  nc_color see_color;
678 
679  bool u_has_radio = player_character.cache_has_item_with_flag( json_flag_TWO_WAY_RADIO, true );
680  bool guy_has_radio = cache_has_item_with_flag( json_flag_TWO_WAY_RADIO, true );
681  // is the NPC even in the same area as the player?
682  if( rl_dist( player_abspos, global_omt_location() ) > 3 ||
683  ( rl_dist( player_character.pos(), pos() ) > SEEX * 2 || !player_character.sees( pos() ) ) ) {
684  if( u_has_radio && guy_has_radio ) {
685  if( !( player_character.pos().z >= 0 && pos().z >= 0 ) &&
686  !( player_character.pos().z == pos().z ) ) {
687  //Early exit
688  can_see = _( "Not within radio range" );
689  see_color = c_light_red;
690  } else {
691  // TODO: better range calculation than just elevation.
692  const int base_range = 200;
693  float send_elev_boost = ( 1 + ( player_character.pos().z * 0.1 ) );
694  float recv_elev_boost = ( 1 + ( pos().z * 0.1 ) );
695  if( ( square_dist( player_character.global_sm_location(),
696  global_sm_location() ) <= base_range * send_elev_boost * recv_elev_boost ) ) {
697  //Direct radio contact, both of their elevation are in effect
698  retval = 2;
699  can_see = _( "Within radio range" );
700  see_color = c_light_green;
701  } else {
702  //contact via camp radio tower
703  int recv_range = base_range * recv_elev_boost;
704  int send_range = base_range * send_elev_boost;
705  const int radio_tower_boost = 5;
706  // find camps that are near player or npc
707  const std::vector<camp_reference> &camps_near_player = overmap_buffer.get_camps_near(
708  player_character.global_sm_location(), send_range * radio_tower_boost );
709  const std::vector<camp_reference> &camps_near_npc = overmap_buffer.get_camps_near(
710  global_sm_location(), recv_range * radio_tower_boost );
711  bool camp_to_npc = false;
712  bool camp_to_camp = false;
713  for( const camp_reference &i : camps_near_player ) {
714  if( !i.camp->has_provides( "radio" ) ) {
715  continue;
716  }
717  if( camp_to_camp ||
718  square_dist( i.abs_sm_pos, global_sm_location() ) <= recv_range * radio_tower_boost ) {
719  //one radio tower relay
720  camp_to_npc = true;
721  break;
722  }
723  for( const camp_reference &j : camps_near_npc ) {
724  //two radio tower relays
725  if( ( j.camp )->has_provides( "radio" ) &&
726  ( square_dist( i.abs_sm_pos, j.abs_sm_pos ) <= base_range * radio_tower_boost *
727  radio_tower_boost ) ) {
728  camp_to_camp = true;
729  break;
730  }
731  }
732  }
733  if( camp_to_npc || camp_to_camp ) {
734  retval = 2;
735  can_see = _( "Within radio range" );
736  see_color = c_light_green;
737  } else {
738  can_see = _( "Not within radio range" );
739  see_color = c_light_red;
740  }
741  }
742  }
743  } else if( guy_has_radio && !u_has_radio ) {
744  can_see = _( "You do not have a radio" );
745  see_color = c_light_red;
746  } else if( !guy_has_radio && u_has_radio ) {
747  can_see = _( "Follower does not have a radio" );
748  see_color = c_light_red;
749  } else {
750  can_see = _( "Both you and follower need a radio" );
751  see_color = c_light_red;
752  }
753  } else {
754  retval = 1;
755  can_see = _( "Within interaction range" );
756  see_color = c_light_green;
757  }
758  // TODO: NPCS on mission contactable same as traveling
759  if( has_companion_mission() ) {
760  can_see = _( "Press enter to recall from their mission." );
761  see_color = c_light_red;
762  }
763  mvwprintz( fac_w, point( width, ++y ), see_color, "%s", can_see );
764  nc_color status_col = col;
765  if( current_target() != nullptr ) {
766  status_col = c_light_red;
767  }
768  mvwprintz( fac_w, point( width, ++y ), status_col, _( "Status: " ) + get_current_status() );
769  if( is_stationed && has_job() ) {
770  mvwprintz( fac_w, point( width, ++y ), col, _( "Working at camp" ) );
771  } else if( is_stationed ) {
772  mvwprintz( fac_w, point( width, ++y ), col, _( "Idling at camp" ) );
773  }
774 
775  const std::pair <std::string, nc_color> condition = hp_description();
776  mvwprintz( fac_w, point( width, ++y ), condition.second, _( "Condition: " ) + condition.first );
777  const std::pair <std::string, nc_color> hunger_pair = display::hunger_text_color( *this );
778  const std::pair <std::string, nc_color> thirst_pair = display::thirst_text_color( *this );
779  const std::pair <std::string, nc_color> sleepiness_pair = display::sleepiness_text_color( *this );
780  const std::string nominal = pgettext( "needs", "Nominal" );
781  mvwprintz( fac_w, point( width, ++y ), hunger_pair.second,
782  _( "Hunger: " ) + ( hunger_pair.first.empty() ? nominal : hunger_pair.first ) );
783  mvwprintz( fac_w, point( width, ++y ), thirst_pair.second,
784  _( "Thirst: " ) + ( thirst_pair.first.empty() ? nominal : thirst_pair.first ) );
785  mvwprintz( fac_w, point( width, ++y ), sleepiness_pair.second,
786  _( "Sleepiness: " ) + ( sleepiness_pair.first.empty() ? nominal : sleepiness_pair.first ) );
787  int lines = fold_and_print( fac_w, point( width, ++y ), getmaxx( fac_w ) - width - 2, c_white,
788  _( "Wielding: " ) + weapname_simple() );
789  y += lines;
790 
791  const auto skillslist = Skill::get_skills_sorted_by( [&]( const Skill & a, const Skill & b ) {
792  const int level_a = get_skill_level( a.ident() );
793  const int level_b = get_skill_level( b.ident() );
794  return localized_compare( std::make_pair( -level_a, a.name() ),
795  std::make_pair( -level_b, b.name() ) );
796  } );
797  size_t count = 0;
798  std::vector<std::string> skill_strs;
799  for( size_t i = 0; i < skillslist.size() && count < 3; i++ ) {
800  if( !skillslist[ i ]->is_combat_skill() ) {
801  std::string skill_str = string_format( "%s: %d", skillslist[i]->name(),
802  static_cast<int>( get_skill_level( skillslist[i]->ident() ) ) );
803  skill_strs.push_back( skill_str );
804  count += 1;
805  }
806  }
807  std::string best_three_noncombat = _( "Best other skills: " );
808  std::string best_skill_text = string_format( _( "Best combat skill: %s: %d" ),
809  best_combat_skill( combat_skills::NO_GENERAL ).first.obj().name(),
811  mvwprintz( fac_w, point( width, ++y ), col, best_skill_text );
812  mvwprintz( fac_w, point( width, ++y ), col, best_three_noncombat + skill_strs[0] );
813  mvwprintz( fac_w, point( width + utf8_width( best_three_noncombat ), ++y ), col, skill_strs[1] );
814  mvwprintz( fac_w, point( width + utf8_width( best_three_noncombat ), ++y ), col, skill_strs[2] );
815  return retval;
816 }
std::string to_string(const time_duration &d, const bool compact)
Returns a string showing a duration.
Definition: calendar.cpp:546
int utf8_width(const std::string_view s, const bool ignore_tags)
std::string weapname_simple() const
Get the formatted name of the currently wielded item (if any) without current gun mode and ammo.
Definition: character.cpp:7942
bool cache_has_item_with_flag(const flag_id &type_flag, bool need_charges=false) const
Find if the character has an item whose type has a specific flag.
Definition: character.cpp:9485
tripoint_abs_sm global_sm_location() const
Returns the location of the creature in global submap coordinates.
Definition: creature.cpp:3237
Definition: skill.h:33
static std::vector< const Skill * > get_skills_sorted_by(std::function< bool(const Skill &, const Skill &)> pred)
Definition: skill.cpp:92
const std::string & camp_name() const
Definition: basecamp.h:178
std::string to_string() const
Definition: coordinates.h:121
std::pair< std::string, nc_color > hp_description() const
Definition: npc.cpp:3417
std::string get_current_status() const
Returns current status (Sleeping, Guarding, In Combat, etc.), or current activity.
Definition: faction.cpp:596
bool has_job() const
Definition: npc.h:1316
std::optional< tripoint_abs_omt > get_mission_destination() const
Definition: npc.cpp:3476
npc_companion_mission get_companion_mission() const
Definition: npc.cpp:3490
std::pair< skill_id, int > best_combat_skill(combat_skills subset) const
Definition: npc.cpp:1033
bool has_companion_mission() const
Definition: npc.cpp:3485
std::vector< camp_reference > get_camps_near(const tripoint_abs_sm &location, int radius)
#define c_white
Definition: color.h:16
#define c_light_gray
Definition: color.h:17
int square_dist(const coords::coord_point< Point, Origin, Scale, LhsInBounds > &loc1, const coords::coord_point< Point, Origin, Scale, RhsInBounds > &loc2)
Definition: coordinates.h:755
static const flag_id json_flag_TWO_WAY_RADIO("TWO_WAY_RADIO")
constexpr int SEEX
std::string direction_name(const direction dir)
Definition: line.cpp:612
constexpr localized_comparator localized_compare
static constexpr double a
Definition: magic.cpp:1566
static constexpr double b
Definition: magic.cpp:1567
std::string action_of(mission_kind kind)
int getmaxx(const window &win)
Definition: ncurses_def.cpp:91
std::pair< std::string, nc_color > sleepiness_text_color(const Character &u)
Definition: display.cpp:747
std::pair< std::string, nc_color > thirst_text_color(const Character &u)
Definition: display.cpp:553
std::pair< std::string, nc_color > hunger_text_color(const Character &u)
Definition: display.cpp:584
void mvwprintz(const catacurses::window &w, const point &p, const nc_color &FG, const std::string &text)
Definition: output.cpp:3290
int fold_and_print(const catacurses::window &w, const point &begin, int width, const nc_color &base_color, const std::string &text, const char split)
Fold and print text in the given window.
Definition: output.cpp:379
mission_kind id
mission_id miss_id
Definition: npc.h:188
int z
Definition: point.h:134
#define pgettext(STRING1, STRING2)
Definition: translations.h:92

References _, a, action_of(), assigned_camp, b, best_combat_skill(), c_light_gray, c_light_green, c_light_red, c_white, Character::cache_has_item_with_flag(), basecamp::camp_name(), companion_mission_time_ret, current_target(), direction_from(), direction_name(), overmapbuffer::find_camp(), fold_and_print(), overmapbuffer::get_camps_near(), get_companion_mission(), get_current_status(), get_mission_destination(), get_player_character(), Character::get_skill_level(), Skill::get_skills_sorted_by(), catacurses::getmaxx(), Creature::global_omt_location(), Creature::global_sm_location(), has_companion_mission(), has_job(), hp_description(), display::hunger_text_color(), mission_id::id, json_flag_TWO_WAY_RADIO, localized_compare, npc_companion_mission::miss_id, mvwprintz(), Character::name, NO_GENERAL, overmap_buffer, pgettext, point, Creature::pos(), rl_dist(), second, Character::sees(), SEEX, display::sleepiness_text_color(), square_dist(), string_format(), display::thirst_text_color(), coords::coord_point_base< Point >::to_string(), to_string(), calendar::turn, utf8_width(), Character::weapname_simple(), and tripoint::z.

Referenced by faction_manager::display().

◆ find_corpse_to_pulp()

bool npc::find_corpse_to_pulp ( )

Returns true if it finds one.

Definition at line 3889 of file npcmove.cpp.

3890 {
3891  Character &player_character = get_player_character();
3892  if( is_player_ally() ) {
3894  player_character.in_vehicle || is_hallucination() ) {
3895  return false;
3896  }
3897  if( rl_dist( pos(), player_character.pos() ) >= mem_combat.engagement_distance ) {
3898  // don't start to pulp corpses if you're already far from the player.
3899  return false;
3900  }
3901  }
3902 
3903  map &here = get_map();
3904  // Pathing with overdraw can get expensive, limit it
3905  int path_counter = 4;
3906  const auto check_tile = [this, &path_counter, &here]( const tripoint & p ) -> const item * {
3907  if( !here.sees_some_items( p, *this ) || !sees( p ) )
3908  {
3909  return nullptr;
3910  }
3911 
3912  const map_stack items = here.i_at( p );
3913  const item *found = nullptr;
3914  for( const item &it : items )
3915  {
3916  // Pulp only stuff that revives, but don't pulp acid stuff
3917  // That is, if you aren't protected from this stuff!
3918  if( it.can_revive() ) {
3919  // If the first encountered corpse bleeds something dangerous then
3920  // it is not safe to bash.
3921  if( is_dangerous_field( field_entry( it.get_mtype()->bloodType(), 1, 0_turns ) ) ) {
3922  return nullptr;
3923  }
3924 
3925  found = &it;
3926  break;
3927  }
3928  }
3929 
3930  if( found != nullptr )
3931  {
3932  path_counter--;
3933  // Only return corpses we can path to
3934  return update_path( p, false, false ) ? found : nullptr;
3935  }
3936 
3937  return nullptr;
3938  };
3939 
3940  const int range = mem_combat.engagement_distance;
3941 
3942  const item *corpse = nullptr;
3943  if( pulp_location && square_dist( get_location(), *pulp_location ) <= range ) {
3944  corpse = check_tile( here.getlocal( *pulp_location ) );
3945  }
3946 
3947  // Find the old target to avoid spamming
3948  const item *old_target = corpse;
3949 
3950  if( corpse == nullptr ) {
3951  // If we're following the player, don't wander off to pulp corpses
3952  const tripoint around = is_walking_with() ? player_character.pos() : pos();
3953  for( const item_location &location : here.get_active_items_in_radius( around, range,
3955  corpse = check_tile( location.position() );
3956 
3957  if( corpse != nullptr ) {
3958  pulp_location = here.getglobal( location.position() );
3959  break;
3960  }
3961 
3962  if( path_counter <= 0 ) {
3963  break;
3964  }
3965  }
3966  }
3967 
3968  if( corpse != nullptr && corpse != old_target && is_walking_with() ) {
3969  std::string talktag = chat_snippets().snip_pulp_zombie.translated();
3970  parse_tags( talktag, get_player_character(), *this );
3971  say( string_format( talktag, corpse->tname() ) );
3972  }
3973 
3974  return corpse != nullptr;
3975 }
tripoint_abs_ms location
The creature's position in absolute coordinates.
Definition: creature.h:776
An active or passive effect existing on a tile.
Definition: field.h:21
Definition: map.h:107
std::list< item_location > get_active_items_in_radius(const tripoint &center, int radius)
Definition: map.cpp:10148
map_stack i_at(const tripoint &p)
Definition: map.cpp:4978
bool sees_some_items(const tripoint &p, const Creature &who) const
Check if creature can see some items at p.
Definition: map.cpp:5855
tripoint_abs_ms getglobal(const tripoint &p) const
Definition: map.cpp:9625

References allow_pulp, chat_snippets(), corpse, npc_combat_memory_cache::engagement_distance, map::get_active_items_in_radius(), Creature::get_location(), get_map(), get_player_character(), map::getglobal(), map::getlocal(), npc_follower_rules::has_flag(), map::i_at(), Character::in_vehicle, Creature::is_dangerous_field(), is_hallucination(), is_player_ally(), is_walking_with(), Creature::location, mem_combat, parse_tags(), Creature::pos(), pulp_location, rl_dist(), rules, say(), Character::sees(), map::sees_some_items(), dialogue_chatbin_snippets::snip_pulp_zombie, square_dist(), string_format(), translation::translated(), and update_path().

Referenced by address_needs().

◆ find_dangerous_explosives()

std::vector< sphere > npc::find_dangerous_explosives ( ) const
private

Definition at line 434 of file npcmove.cpp.

435 {
436  std::vector<sphere> result;
437 
438  const auto active_items = get_map().get_active_items_in_radius( pos(), MAX_VIEW_DISTANCE,
440 
441  for( const item_location &elem : active_items ) {
442  const use_function *use = elem->type->get_use( "explosion" );
443 
444  if( !use ) {
445  continue;
446  }
447 
448  const explosion_iuse *actor = dynamic_cast<const explosion_iuse *>( use->get_actor_ptr() );
449  const int safe_range = actor->explosion.safe_range();
450 
451  if( rl_dist( pos(), elem.position() ) >= safe_range ) {
452  continue; // Far enough.
453  }
454 
455  const int turns_to_evacuate = 2 * safe_range / speed_rating();
456 
457  if( elem->charges > turns_to_evacuate ) {
458  continue; // Consider only imminent dangers.
459  }
460 
461  result.emplace_back( elem.position(), safe_range );
462  }
463 
464  return result;
465 }
void use(int inventory_position)
Uses a tool.
This is a iuse_actor for active items that explode when their charges reaches 0.
Definition: iuse_actor.h:193
explosion_data explosion
Definition: iuse_actor.h:197
float speed_rating() const override
Returns an approximate number of tiles this creature can travel per turn.
Definition: npc.cpp:3167
constexpr int MAX_VIEW_DISTANCE
int safe_range() const
Returns the distance at which the power drops below 1.
Definition: explosion.cpp:1001

References explosion_iuse::explosion, explosive, map::get_active_items_in_radius(), get_map(), MAX_VIEW_DISTANCE, Creature::pos(), rl_dist(), explosion_data::safe_range(), speed_rating(), and Character::use().

Referenced by regen_ai_cache().

◆ find_item()

void npc::find_item ( )

Definition at line 3492 of file npcmove.cpp.

3493 {
3494  if( is_hallucination() ) {
3495  see_item_say_smth( itype_thorazine, chat_snippets().snip_no_to_thorazine.translated() );
3496  see_item_say_smth( itype_lsd, chat_snippets().snip_yes_to_lsd.translated() );
3497  return;
3498  }
3499 
3501  // Grabbing stuff not allowed by our "owner"
3503  "%s considered picking something up but player said not to.", name );
3504  return;
3505  }
3506 
3507  fetching_item = false;
3508  wanted_item = {};
3509  int best_value = minimum_item_value();
3510  // Not perfect, but has to mirror pickup code
3511  units::volume volume_allowed = volume_capacity() - volume_carried();
3512  units::mass weight_allowed = weight_capacity() - weight_carried();
3513  // For some reason range limiting by vision doesn't work properly
3514  const int range = 6;
3515  //int range = sight_range( g->light_level( posz() ) );
3516  //range = std::max( 1, std::min( 12, range ) );
3517 
3518  if( volume_allowed <= 0_ml || weight_allowed <= 0_gram ) {
3519  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s considered picking something up, but no storage left.",
3520  name );
3521  return;
3522  }
3523 
3524  const auto consider_item =
3525  [&best_value, this]
3526  ( const item & it, const tripoint & p ) {
3527  if( ::good_for_pickup( it, *this, p ) ) {
3528  wanted_item_pos = p;
3529  best_value = has_item_whitelist() ? 1000 : value( it );
3530  return true;
3531  } else {
3532  return false;
3533  }
3534  };
3535 
3536  map &here = get_map();
3537  // Harvest item doesn't exist, so we'll be checking by its name
3538  std::string wanted_name;
3539  const auto consider_terrain =
3540  [ this, volume_allowed, &wanted_name, &here ]( const tripoint & p ) {
3541  // We only want to pick plants when there are no items to pick
3542  if( !has_item_whitelist() || wanted_item.get_item() != nullptr || !wanted_name.empty() ||
3543  volume_allowed < 250_ml ) {
3544  return;
3545  }
3546 
3547  const auto &harvest = here.get_harvest_names( p );
3548  for( const auto &entry : harvest ) {
3549  if( item_name_whitelisted( entry ) ) {
3550  wanted_name = entry;
3551  wanted_item_pos = p;
3552  break;
3553  }
3554  }
3555  };
3556 
3557  for( const tripoint &p : closest_points_first( pos(), range ) ) {
3558  // TODO: Make this sight check not overdraw nearby tiles
3559  // TODO: Optimize that zone check
3560  if( is_player_ally() && g->check_zone( zone_type_NO_NPC_PICKUP, p ) ) {
3562  "%s didn't pick up an item because it's in a no-pickup zone.", name );
3563  continue;
3564  }
3565 
3566  const tripoint abs_p = get_location().raw() - pos() + p;
3567  const int prev_num_items = ai_cache.searched_tiles.get( abs_p, -1 );
3568  // Prefetch the number of items present so we can bail out if we already checked here.
3569  map_stack m_stack = here.i_at( p );
3570  int num_items = m_stack.size();
3571  const optional_vpart_position vp = here.veh_at( p );
3572  if( vp ) {
3573  if( const std::optional<vpart_reference> vp_cargo = vp.cargo() ) {
3574  num_items += vp_cargo->items().size();
3575  }
3576  }
3577  if( prev_num_items == num_items ) {
3578  continue;
3579  }
3580  auto cache_tile = [this, &abs_p, num_items]() {
3581  if( wanted_item.get_item() == nullptr ) {
3582  ai_cache.searched_tiles.insert( 1000, abs_p, num_items );
3583  }
3584  };
3585  bool can_see = false;
3586  if( here.sees_some_items( p, *this ) && sees( p ) ) {
3587  can_see = true;
3588  for( item &it : m_stack ) {
3589  if( consider_item( it, p ) ) {
3590  wanted_item = item_location{ map_cursor{p}, &it };
3591  }
3592  }
3593  }
3594 
3595  // Not cached because it gets checked once and isn't expected to change.
3596  if( can_see || sees( p ) ) {
3597  can_see = true;
3598  consider_terrain( p );
3599  }
3600 
3601  if( !vp || vp->vehicle().is_moving() || !( can_see || sees( p ) ) ) {
3602  cache_tile();
3603  continue;
3604  }
3605  const std::optional<vpart_reference> cargo = vp.cargo();
3606  static const std::string locked_string( "LOCKED" );
3607  // TODO: Let player know what parts are safe from NPC thieves
3608  if( !cargo || cargo->has_feature( locked_string ) ) {
3609  cache_tile();
3610  continue;
3611  }
3612 
3613  static const std::string cargo_locking_string( "CARGO_LOCKING" );
3614  if( vp.part_with_feature( cargo_locking_string, true ) ) {
3615  cache_tile();
3616  continue;
3617  }
3618 
3619  for( item &it : cargo->items() ) {
3620  if( consider_item( it, p ) ) {
3621  wanted_item = { vehicle_cursor{ cargo->vehicle(), static_cast<ptrdiff_t>( cargo->part_index() ) }, &it };
3622  }
3623  }
3624  cache_tile();
3625  }
3626 
3627  if( wanted_item.get_item() != nullptr ) {
3628  wanted_name = wanted_item->tname();
3629  }
3630 
3631  if( wanted_name.empty() ) {
3632  return;
3633  }
3634 
3635  fetching_item = true;
3636 
3637  // TODO: Move that check above, make it multi-target pathing and use it
3638  // to limit tiles available for choice of items
3639  const int dist_to_item = rl_dist( wanted_item_pos, pos() );
3640  if( const std::optional<tripoint> dest = nearest_passable( wanted_item_pos, pos() ) ) {
3641  update_path( *dest );
3642  }
3643 
3644  if( path.empty() && dist_to_item > 1 ) {
3645  // Item not reachable, let's just totally give up for now
3646  fetching_item = false;
3647  wanted_item = {};
3648  }
3649 
3650  if( fetching_item && rl_dist( wanted_item_pos, pos() ) > 1 && is_walking_with() ) {
3651  say( _( "Hold on, I want to pick up that %s." ), wanted_name );
3652  }
3653 }
units::volume volume_capacity() const
Definition: character.cpp:8778
units::volume volume_carried() const
Definition: character.cpp:8814
size_t size() const
Definition: item_stack.cpp:14
void insert(int limit, const Key &, const Value &)
Definition: lru_cache.h:48
Value get(const Key &, const Value &default_) const
Definition: lru_cache.h:28
const std::set< std::string > & get_harvest_names(const tripoint &p) const
Returns names of the items that would be dropped.
Definition: map.cpp:2175
double value(const item &it) const
Definition: npc.cpp:2050
bool item_name_whitelisted(const std::string &to_match)
Definition: npctalk.cpp:7224
item_location wanted_item
Definition: npc.h:1367
bool has_item_whitelist() const
Definition: npctalk.cpp:7219
int minimum_item_value() const
Definition: npc.cpp:2032
void see_item_say_smth(const itype_id &object, const std::string &smth)
Definition: npcmove.cpp:3478
std::optional< vpart_reference > part_with_feature(const std::string &f, bool unbroken) const
Definition: vehicle.cpp:2698
std::optional< vpart_reference > cargo() const
Definition: vehicle.cpp:2710
bool good_for_pickup(const item &it, npc &who, const tripoint &there)
Definition: npcmove.cpp:219
static std::optional< tripoint > nearest_passable(const tripoint &p, const tripoint &closest_to)
Definition: npcmove.cpp:3401
static const itype_id itype_lsd("lsd")
static const itype_id itype_thorazine("thorazine")
static const zone_type_id zone_type_NO_NPC_PICKUP("NO_NPC_PICKUP")
lru_cache< tripoint, int > searched_tiles
Definition: npc.h:593

References _, add_msg_debug, ai_cache, allow_pick_up, optional_vpart_position::cargo(), chat_snippets(), closest_points_first(), debugmode::DF_NPC_ITEMAI, item::empty(), fetching_item, g, lru_cache< Key, Value >::get(), map::get_harvest_names(), item_location::get_item(), Creature::get_location(), get_map(), anonymous_namespace{npcmove.cpp}::good_for_pickup(), harvest, npc_follower_rules::has_flag(), has_item_whitelist(), map::i_at(), lru_cache< Key, Value >::insert(), is_hallucination(), is_player_ally(), is_walking_with(), item_name_whitelisted(), itype_lsd, itype_thorazine, minimum_item_value(), Character::name, nearest_passable(), optional_vpart_position::part_with_feature(), path, Creature::pos(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), rl_dist(), rules, say(), npc_short_term_cache::searched_tiles, see_item_say_smth(), Character::sees(), map::sees_some_items(), item_stack::size(), item::tname(), update_path(), value(), map::veh_at(), Character::volume_capacity(), Character::volume_carried(), wanted_item, wanted_item_pos, Character::weight_capacity(), Character::weight_carried(), and zone_type_NO_NPC_PICKUP.

Referenced by move().

◆ find_job_to_perform()

bool npc::find_job_to_perform ( )

Definition at line 3262 of file npcmove.cpp.

3263 {
3264  // cleanup history
3265  auto fetch_itr = job.fetch_history.begin();
3266  while( fetch_itr != job.fetch_history.end() ) {
3267  if( fetch_itr->second != calendar::turn ) {
3268  fetch_itr = job.fetch_history.erase( fetch_itr );
3269  } else {
3270  fetch_itr++;
3271  }
3272  }
3273 
3274  for( activity_id &elem : job.get_prioritised_vector() ) {
3275  if( job.get_priority_of_job( elem ) == 0 ) {
3276  continue;
3277  }
3278  player_activity scan_act = player_activity( elem );
3279  if( elem == ACT_MOVE_LOOT ) {
3280  assign_activity( elem );
3281  } else if( generic_multi_activity_handler( scan_act, *this->as_character(), true ) ) {
3282  assign_activity( elem );
3283  return true;
3284  }
3285  }
3286  return false;
3287 }
std::vector< activity_id > get_prioritised_vector() const
Definition: npc.cpp:202
std::unordered_map< std::string, time_point > fetch_history
Definition: npc.h:160
int get_priority_of_job(const activity_id &req_job) const
Definition: npc.cpp:192
job_data job
Definition: npc.h:1416
static const activity_id ACT_MOVE_LOOT("ACT_MOVE_LOOT")

References ACT_MOVE_LOOT, Character::as_character(), Character::assign_activity(), job_data::fetch_history, generic_multi_activity_handler(), job_data::get_prioritised_vector(), job_data::get_priority_of_job(), job, and calendar::turn.

Referenced by move().

◆ find_reloadable()

item_location npc::find_reloadable ( )

Has a gun or magazine that can be reloaded.

Definition at line 2108 of file npcmove.cpp.

2109 {
2110  auto cached_value = cached_info.find( "reloadables" );
2111  if( cached_value != cached_info.end() ) {
2112  return item_location();
2113  }
2114  // Check wielded gun, non-wielded guns, mags and tools
2115  // TODO: Build a proper gun->mag->ammo DAG (Directed Acyclic Graph)
2116  // to avoid checking same properties over and over
2117  // TODO: Make this understand bandoliers, pouches etc.
2118  // TODO: Cache items checked for reloading to avoid re-checking same items every turn
2119  // TODO: Make it understand smaller and bigger magazines
2120  item_location reloadable;
2121  visit_items( [this, &reloadable]( item * node, item * parent ) {
2122  if( !wants_to_reload( *this, *node ) ) {
2123  return VisitResponse::NEXT;
2124  }
2125 
2126  item_location node_loc = form_loc_recursive( this, node, parent );
2127 
2128  const item_location it_loc = select_ammo( node_loc ).ammo;
2129  if( it_loc && wants_to_reload_with( *node, *it_loc ) ) {
2130  reloadable = node_loc;
2131  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s has decided to reload %s!", name, node->tname() );
2132  return VisitResponse::ABORT;
2133  }
2134 
2135  return VisitResponse::NEXT;
2136  } );
2137 
2138  if( reloadable ) {
2139  return reloadable;
2140  }
2141 
2142  cached_info.emplace( "reloadables", 0.0 );
2143  return item_location();
2144 }
std::map< std::string, double > cached_info
Definition: character.h:3898
static item_location form_loc_recursive(Character *npc, item *node, item *parent)
Definition: npcmove.cpp:2099
static bool wants_to_reload_with(const item &weap, const item &ammo)
Definition: npcmove.cpp:2093

References ABORT, add_msg_debug, item::reload_option::ammo, Character::cached_info, debugmode::DF_NPC_ITEMAI, form_loc_recursive(), Character::name, NEXT, select_ammo(), item::tname(), Character::visit_items(), wants_to_reload(), and wants_to_reload_with().

Referenced by address_needs().

◆ find_usable_ammo() [1/2]

item_location npc::find_usable_ammo ( const item_location weap)

Finds ammo the NPC could use to reload a given object.

Definition at line 2156 of file npcmove.cpp.

2157 {
2158  if( !can_reload( *weap ) ) {
2159  return item_location();
2160  }
2161 
2162  item_location loc = select_ammo( weap ).ammo;
2163  if( !loc || !wants_to_reload_with( *weap, *loc ) ) {
2164  return item_location();
2165  }
2166 
2167  return loc;
2168 }
bool can_reload(const item &it, const item *ammo=nullptr) const
Whether a tool or gun is potentially reloadable (optionally considering a specific ammo)

References item::reload_option::ammo, Character::can_reload(), select_ammo(), and wants_to_reload_with().

Referenced by can_reload_current(), and find_usable_ammo().

◆ find_usable_ammo() [2/2]

item_location npc::find_usable_ammo ( const item_location weap) const

Definition at line 2170 of file npcmove.cpp.

2171 {
2172  return const_cast<npc *>( this )->find_usable_ammo( weap );
2173 }

References find_usable_ammo().

◆ follow_distance()

int npc::follow_distance ( ) const

Definition at line 2534 of file npc.cpp.

2535 {
2536  Character &player_character = get_player_character();
2537  map &here = get_map();
2538  // HACK: If the player is standing on stairs, follow closely
2539  // This makes the stair hack less painful to use
2540  if( is_walking_with() &&
2541  ( here.has_flag( ter_furn_flag::TFLAG_GOES_DOWN, player_character.pos() ) ||
2542  here.has_flag( ter_furn_flag::TFLAG_GOES_UP, player_character.pos() ) ) ) {
2543  return 1;
2544  }
2545  // Uses ally_rule follow_distance_2 to determine if should follow by 2 or 4 tiles
2547  return 2;
2548  }
2549  // If NPC doesn't see player, change follow distance to 2
2550  if( !sees( player_character ) ) {
2551  return 2;
2552  }
2553  return 4;
2554 }
@ follow_distance_2

References follow_distance_2, get_map(), get_player_character(), npc_follower_rules::has_flag(), map::has_flag(), is_walking_with(), Creature::pos(), rules, Character::sees(), TFLAG_GOES_DOWN, and TFLAG_GOES_UP.

Referenced by assess_danger(), execute_action(), good_escape_direction(), and move().

◆ form_opinion()

void npc::form_opinion ( const Character you)

Definition at line 1397 of file npc.cpp.

1398 {
1399  op_of_u = get_opinion_values( you );
1400 
1401  decide_needs();
1402  for( const npc_need &i : needs ) {
1403  if( i == need_food || i == need_drink ) {
1404  op_of_u.value += 2;
1405  }
1406  }
1407 
1408  if( op_of_u.fear < personality.bravery + 10 &&
1409  op_of_u.fear - personality.aggression > -10 && op_of_u.trust > -8 ) {
1411  } else if( op_of_u.fear - 2 * personality.aggression - personality.bravery < -30 ) {
1413  } else if( my_fac && my_fac->likes_u < -10 ) {
1414  if( is_player_ally() ) {
1415  mutiny();
1416  }
1418  } else {
1420  }
1421 
1422  add_msg_debug( debugmode::DF_NPC, "%s formed an opinion of you: %s", get_name(),
1424 }
void decide_needs()
Definition: npc.cpp:1670
void mutiny()
Definition: npc.cpp:1540
npc_opinion op_of_u
Definition: npc.h:1403
npc_opinion get_opinion_values(const Character &you) const
Definition: npc.cpp:1426
std::string npc_attitude_id(npc_attitude att)
Definition: npc.cpp:2917
int value
Definition: npc.h:235
int trust
Definition: npc.h:233
int fear
Definition: npc.h:234

References add_msg_debug, npc_personality::aggression, attitude, npc_personality::bravery, decide_needs(), debugmode::DF_NPC, npc_opinion::fear, Character::get_name(), get_opinion_values(), is_player_ally(), faction_template::likes_u, mutiny(), Character::my_fac, need_drink, need_food, needs, npc_attitude_id(), NPCATT_FLEE_TEMP, NPCATT_KILL, NPCATT_TALK, op_of_u, personality, set_attitude(), npc_opinion::trust, and npc_opinion::value.

◆ generate_personality_traits()

void npc::generate_personality_traits ( )

Definition at line 706 of file npc.cpp.

707 {
709  for( const mutation_branch &mdata : mutation_branch::get_all() ) {
710  if( mdata.personality_score ) {
711  const auto &required = mdata.personality_score;
712  // This looks intimidating, but it's really just a bounds check, repeated for every personality score.
713  if( ( required->min_aggression <= ur.aggression && ur.aggression <= required->max_aggression ) &&
714  ( required->min_bravery <= ur.bravery && ur.bravery <= required->max_bravery ) &&
715  ( required->min_collector <= ur.collector && ur.collector <= required->max_collector ) &&
716  ( required->min_altruism <= ur.altruism && ur.altruism <= required->max_altruism ) ) {
717  set_mutation( mdata.id );
718  }
719  }
720  }
721 }
void set_mutation(const trait_id &, const mutation_variant *=nullptr)
Definition: mutation.cpp:283
static const std::vector< mutation_branch > & get_all()
All known mutations.
int8_t altruism
Definition: npc.h:220
int8_t collector
Definition: npc.h:219

References npc_personality::aggression, npc_personality::altruism, npc_personality::bravery, npc_personality::collector, mutation_branch::get_all(), personality, and Character::set_mutation().

Referenced by randomize().

◆ get_attitude()

npc_attitude npc::get_attitude ( ) const
overridevirtual

◆ get_attitude_group()

attitude_group npc::get_attitude_group ( npc_attitude  att) const

Definition at line 3495 of file npc.cpp.

3496 {
3497  switch( att ) {
3498  case NPCATT_MUG:
3499  case NPCATT_WAIT_FOR_LEAVE:
3500  case NPCATT_KILL:
3501  return attitude_group::hostile;
3502  case NPCATT_FLEE:
3503  case NPCATT_FLEE_TEMP:
3504  return attitude_group::fearful;
3505  case NPCATT_FOLLOW:
3506  case NPCATT_ACTIVITY:
3507  case NPCATT_LEAD:
3508  return attitude_group::friendly;
3509  default:
3510  break;
3511  }
3512  return attitude_group::neutral;
3513 }
@ NPCATT_ACTIVITY
Definition: npc.h:124
@ NPCATT_FOLLOW
Definition: npc.h:110

References fearful, friendly, hostile, neutral, NPCATT_ACTIVITY, NPCATT_FLEE, NPCATT_FLEE_TEMP, NPCATT_FOLLOW, NPCATT_KILL, NPCATT_LEAD, NPCATT_MUG, and NPCATT_WAIT_FOR_LEAVE.

Referenced by handle_sound(), is_ally(), and set_attitude().

◆ get_cached_friends()

const std::vector< weak_ptr_fast< Creature > > & npc::get_cached_friends ( ) const

Definition at line 2954 of file npc.cpp.

2955 {
2956  return ai_cache.friends;
2957 }

References ai_cache, and npc_short_term_cache::friends.

Referenced by indoor_voice().

◆ get_companion_mission()

npc_companion_mission npc::get_companion_mission ( ) const

Definition at line 3490 of file npc.cpp.

3491 {
3492  return comp_mission;
3493 }
npc_companion_mission comp_mission
Definition: npc.h:1475

References comp_mission.

Referenced by companion_per_recipe_building_type(), faction_display(), and update_emergency_recall().

◆ get_current_activity()

std::string npc::get_current_activity ( ) const

Returns the current activity name (reading, disassembling, etc.), or "nothing".

Definition at line 3786 of file npc.cpp.

3787 {
3788  if( current_activity_id ) {
3789  return current_activity_id.obj().verb().translated();
3790  } else {
3791  return _( "nothing" );
3792  }
3793 }
const translation & verb() const
Definition: activity_type.h:73

References _, current_activity_id, string_id< T >::obj(), translation::translated(), and activity_type::verb().

Referenced by get_current_status(), name_and_activity(), and parse_tags().

◆ get_current_attack()

const std::shared_ptr<npc_attack>& npc::get_current_attack ( ) const
inline

Definition at line 1352 of file npc.h.

1352  {
1353  return ai_cache.current_attack;
1354  }

References ai_cache, and npc_short_term_cache::current_attack.

◆ get_current_attack_evaluation()

const npc_attack_rating& npc::get_current_attack_evaluation ( ) const
inline

Definition at line 1356 of file npc.h.

1356  {
1358  }

References ai_cache, and npc_short_term_cache::current_attack_evaluation.

◆ get_current_status()

std::string npc::get_current_status ( ) const

Returns current status (Sleeping, Guarding, In Combat, etc.), or current activity.

Definition at line 596 of file faction.cpp.

597 {
598  if( current_target() != nullptr ) {
599  return _( "In Combat!" );
600  } else if( in_sleep_state() ) {
601  return _( "Sleeping" );
602  } else if( is_following() ) {
603  return _( "Following" );
604  } else if( is_leader() ) {
605  return _( "Leading" );
606  } else if( is_patrolling() ) {
607  return _( "Patrolling" );
608  } else if( is_guarding() ) {
609  return _( "Guarding" );
610  } else {
611  return get_current_activity();
612  }
613 }
bool is_patrolling() const
Definition: npc.cpp:2371
std::string get_current_activity() const
Returns the current activity name (reading, disassembling, etc.), or "nothing".
Definition: npc.cpp:3786

References _, current_target(), get_current_activity(), Character::in_sleep_state(), is_following(), is_guarding(), is_leader(), and is_patrolling().

Referenced by faction_display().

◆ get_epilogue()

std::string npc::get_epilogue ( ) const

Definition at line 3404 of file npc.cpp.

3405 {
3407  male ? "epilogue_npc_male" : "epilogue_npc_female"
3408  ).value_or( translation() ).translated();
3409 }
bool male
Definition: character.h:2687
std::optional< translation > random_from_category(const std::string &cat) const
Returns a random snippet out of the given category.
Class for storing translation context and raw string for deferred translation.
Definition: translation.h:18
snippet_library SNIPPET

References Character::male, snippet_library::random_from_category(), and SNIPPET.

◆ get_fac_id()

faction_id npc::get_fac_id ( ) const

◆ get_faction()

faction * npc::get_faction ( ) const
overridevirtual

Reimplemented from Character.

Definition at line 776 of file npc.cpp.

777 {
778  if( !my_fac ) {
779  return g->faction_manager_ptr->get( faction_no_faction );
780  }
781  return my_fac;
782 }
static const faction_id faction_no_faction("no_faction")

References faction_no_faction, g, and Character::my_fac.

Referenced by talker_npc::add_faction_rep(), shopkeeper_item_group::can_sell(), debug_menu::character_edit_menu(), get_price_rules(), is_ally(), talk_function::mission_success(), starting_weapon(), talker_npc::will_talk_to_u(), and would_take_that().

◆ get_faction_ver()

int npc::get_faction_ver ( ) const

Definition at line 2239 of file npc.cpp.

2240 {
2241  return faction_api_version;
2242 }
int faction_api_version
Definition: character.h:3956

References Character::faction_api_version.

Referenced by debug_menu::character_edit_menu(), and update_faction_api().

◆ get_healing_item()

item & npc::get_healing_item ( healing_options  try_to_fix,
bool  first_best = false 
)

Definition at line 2200 of file npc.cpp.

2201 {
2202  item *best = &null_item_reference();
2203  visit_items( [&best, try_to_fix, first_best]( item * node, item * ) {
2204  const use_function *use = node->type->get_use( "heal" );
2205  if( use == nullptr ) {
2206  return VisitResponse::NEXT;
2207  }
2208 
2209  const heal_actor &actor = dynamic_cast<const heal_actor &>( *use->get_actor_ptr() );
2210  if( ( try_to_fix.bandage && actor.bandages_power > 0.0f ) ||
2211  ( try_to_fix.disinfect && actor.disinfectant_power > 0.0f ) ||
2212  ( try_to_fix.bleed && actor.bleed > 0 ) ||
2213  ( try_to_fix.bite && actor.bite > 0 ) ||
2214  ( try_to_fix.infect && actor.infect > 0 ) ) {
2215  best = node;
2216  if( first_best ) {
2217  return VisitResponse::ABORT;
2218  }
2219  }
2220 
2221  return VisitResponse::NEXT;
2222  } );
2223 
2224  return *best;
2225 }
float infect
Chance to remove infected effect.
Definition: iuse_actor.h:885
float disinfectant_power
How many intensity levels will be applied when healing limbs?
Definition: iuse_actor.h:877
float bandages_power
How many intensity levels will be applied when healing limbs?
Definition: iuse_actor.h:873
float bite
Chance to remove bite effect.
Definition: iuse_actor.h:883
int bleed
How many levels of bleeding effect intensity can it remove (dressing efficiency).
Definition: iuse_actor.h:881
bool bandage
Definition: npc.h:550
bool bleed
Definition: npc.h:552
bool infect
Definition: npc.h:554
bool bite
Definition: npc.h:553
bool disinfect
Definition: npc.h:551
const use_function * get_use(const std::string &iuse_name) const
Definition: itype.cpp:179

References ABORT, healing_options::bandage, heal_actor::bandages_power, heal_actor::bite, healing_options::bite, heal_actor::bleed, healing_options::bleed, healing_options::disinfect, heal_actor::disinfectant_power, itype::get_use(), heal_actor::infect, healing_options::infect, NEXT, null_item_reference(), item::type, Character::use(), and Character::visit_items().

Referenced by has_healing_item(), heal_player(), and heal_self().

◆ get_item_to_craft()

item_location npc::get_item_to_craft ( )

Definition at line 3087 of file crafting.cpp.

3088 {
3089  // check inventory
3090  item_location to_craft;
3091  visit_items( [ this, &to_craft ]( item * itm, item * ) {
3092  if( itm->get_var( "crafter", "" ) == name ) {
3093  to_craft = item_location( *this, itm );
3094  if( !is_anyone_crafting( to_craft, this ) ) {
3095  return VisitResponse::ABORT;
3096  }
3097  }
3098  return VisitResponse::NEXT;
3099  } );
3100  if( to_craft ) {
3101  return to_craft;
3102  }
3103 
3104  // check items around npc
3105  map &here = get_map();
3106  for( const tripoint &adj : here.points_in_radius( pos(), 1 ) ) {
3107  if( here.dangerous_field_at( adj ) ) {
3108  continue;
3109  }
3110  for( item &itm : here.i_at( adj ) ) {
3111  if( itm.get_var( "crafter", "" ) == name ) {
3112  to_craft = item_location( map_cursor( adj ), &itm );
3113  if( !is_anyone_crafting( to_craft, this ) ) {
3114  return to_craft;
3115  }
3116  }
3117  }
3118  if( const std::optional<vpart_reference> vp = here.veh_at( adj ).cargo() ) {
3119  for( item &itm : vp->items() ) {
3120  if( itm.get_var( "crafter", "" ) == name ) {
3121  to_craft = item_location( vehicle_cursor( vp->vehicle(), vp->part_index() ), &itm );
3122  if( !is_anyone_crafting( to_craft, this ) ) {
3123  return to_craft;
3124  }
3125  }
3126  }
3127  }
3128  }
3129  return to_craft;
3130 }
bool dangerous_field_at(const tripoint &p)
Definition: map.cpp:6536

References item::get_var(), Character::name, NEXT, and Character::visit_items().

Referenced by can_do_activity_there(), and generic_multi_activity_do().

◆ get_known_to_u()

bool npc::get_known_to_u ( ) const

Definition at line 947 of file npc.cpp.

948 {
949  return known_to_u;
950 }
bool known_to_u
Definition: npc.h:1344

References known_to_u.

◆ get_location_for()

overmap_location_str_id npc::get_location_for ( const npc_need need)
static

Definition at line 3253 of file npc.cpp.

3254 {
3255  return need_data[static_cast<size_t>( need )].second;
3256 }
static std::array< std::pair< std::string, overmap_location_str_id >, npc_need::num_needs > need_data
Definition: npc.h:1136

References need_data, and second.

Referenced by set_omt_destination().

◆ get_mission_destination()

std::optional< tripoint_abs_omt > npc::get_mission_destination ( ) const

Definition at line 3476 of file npc.cpp.

3477 {
3478  if( comp_mission.destination ) {
3479  return comp_mission.destination;
3480  } else {
3481  return std::nullopt;
3482  }
3483 }
std::optional< tripoint_abs_omt > destination
Definition: npc.h:191

References comp_mission, and npc_companion_mission::destination.

Referenced by faction_display().

◆ get_monster_faction()

mfaction_id npc::get_monster_faction ( ) const
overridevirtual

For mutant NPCs.

Returns how monsters perceive said NPC. Doesn't imply NPC sees them the same.

Implements Creature.

Definition at line 3352 of file npc.cpp.

3353 {
3354  if( my_fac ) {
3355  if( my_fac->mon_faction.is_valid() ) {
3356  return my_fac->mon_faction;
3357  }
3358  }
3359 
3360  // legacy checks
3361  if( is_player_ally() ) {
3362  return monfaction_player.id();
3363  }
3364 
3365  if( has_trait( trait_BEE ) ) {
3366  return monfaction_bee.id();
3367  }
3368 
3369  return monfaction_human.id();
3370 }
mfaction_str_id mon_faction
Definition: faction.h:122
bool is_valid() const
Returns whether this id is valid, that means whether it refers to an existing object.
Definition: achievement.cpp:78
int_id< T > id() const
Translate the string based it to the matching integer based id.
Definition: ammo_effect.cpp:54
static const mfaction_str_id monfaction_human("human")
static const mfaction_str_id monfaction_player("player")
static const mfaction_str_id monfaction_bee("bee")
static const trait_id trait_BEE("BEE")

References Character::has_trait(), string_id< T >::id(), is_player_ally(), string_id< T >::is_valid(), faction_template::mon_faction, monfaction_bee, monfaction_human, monfaction_player, Character::my_fac, and trait_BEE.

◆ get_need_str_id()

std::string npc::get_need_str_id ( const npc_need need)
static

Definition at line 3248 of file npc.cpp.

3249 {
3250  return need_data[static_cast<size_t>( need )].first;
3251 }

References need_data.

Referenced by debug_menu::character_edit_menu(), operator<<(), and set_omt_destination().

◆ get_opinion_values()

npc_opinion npc::get_opinion_values ( const Character you) const
Strength increases NPC fear of the player

Definition at line 1426 of file npc.cpp.

1427 {
1428  npc_opinion npc_values = op_of_u;
1429 
1430  const item_location weapon = you.get_wielded_item();
1431  // FEAR
1432  if( !you.is_armed() ) {
1433  // Unarmed, but actually unarmed ("unarmed weapons" are not unarmed)
1434  npc_values.fear -= 3;
1435  } else if( weapon->is_gun() ) {
1436  // TODO: Make bows not guns
1438  npc_values.fear += 2;
1439  } else {
1440  npc_values.fear += 6;
1441  }
1442  } else if( you.weapon_value( *weapon ) > 20 ) {
1443  npc_values.fear += 2;
1444  }
1445 
1446  ///\EFFECT_STR increases NPC fear of the player
1447  npc_values.fear += ( you.str_max / 4 ) - 2;
1448 
1449  // is your health low
1450  for( const std::pair<const bodypart_str_id, bodypart> &elem : get_player_character().get_body() ) {
1451  const int hp_max = elem.second.get_hp_max();
1452  const int hp_cur = elem.second.get_hp_cur();
1453  if( hp_cur <= hp_max / 2 ) {
1454  npc_values.fear--;
1455  }
1456  }
1457 
1458  // is my health low
1459  for( const std::pair<const bodypart_str_id, bodypart> &elem : get_body() ) {
1460  const int hp_max = elem.second.get_hp_max();
1461  const int hp_cur = elem.second.get_hp_cur();
1462  if( hp_cur <= hp_max / 2 ) {
1463  npc_values.fear++;
1464  }
1465  }
1466 
1467  if( you.has_flag( json_flag_SAPIOVORE ) ) {
1468  npc_values.fear += 10; // Sapiovores = Scary
1469  }
1470  if( you.has_trait( trait_TERRIFYING ) ) {
1471  npc_values.fear += 6;
1472  }
1473 
1474  int u_ugly = 0;
1475  for( trait_id &mut : you.get_mutations() ) {
1476  u_ugly += mut.obj().ugliness;
1477  }
1478  for( const bodypart_id &bp : you.get_all_body_parts() ) {
1479  if( bp->ugliness == 0 && bp->ugliness_mandatory == 0 ) {
1480  continue;
1481  }
1482  u_ugly += bp->ugliness_mandatory;
1483  u_ugly += bp->ugliness - ( bp->ugliness * worn.get_coverage( bp ) / 100 );
1484  u_ugly = enchantment_cache->modify_value( enchant_vals::mod::UGLINESS, u_ugly );
1485  }
1486  npc_values.fear += u_ugly / 2;
1487  npc_values.trust -= u_ugly / 3;
1488 
1489  if( you.get_stim() > 20 ) {
1490  npc_values.fear++;
1491  }
1492 
1493  if( you.has_effect( effect_drunk ) ) {
1494  npc_values.fear -= 2;
1495  }
1496 
1497  // TRUST
1498  if( op_of_u.fear > 0 ) {
1499  npc_values.trust -= 3;
1500  } else {
1501  npc_values.trust += 1;
1502  }
1503 
1504  if( weapon && weapon->is_gun() ) {
1505  npc_values.trust -= 2;
1506  } else if( !you.is_armed() ) {
1507  npc_values.trust += 2;
1508  }
1509 
1510  // TODO: More effects
1511  if( you.has_effect( effect_high ) ) {
1512  npc_values.trust -= 1;
1513  }
1514  if( you.has_effect( effect_drunk ) ) {
1515  npc_values.trust -= 2;
1516  }
1517  if( you.get_stim() > 20 || you.get_stim() < -20 ) {
1518  npc_values.trust -= 1;
1519  }
1520  if( you.get_painkiller() > 30 ) {
1521  npc_values.trust -= 1;
1522  }
1523 
1524  if( op_of_u.trust > 0 ) {
1525  // Trust is worth a lot right now
1526  npc_values.trust /= 2;
1527  }
1528 
1529  // VALUE
1530  npc_values.value = 0;
1531  for( const std::pair<const bodypart_str_id, bodypart> &elem : get_body() ) {
1532  if( elem.second.get_hp_cur() < elem.second.get_hp_max() * 0.8f ) {
1533  npc_values.value++;
1534  }
1535  }
1536 
1537  return npc_values;
1538 }
int get_painkiller() const
Returns intensity of painkillers
Definition: character.cpp:9839
int get_stim() const
Definition: character.cpp:6742
pimpl< enchant_cache > enchantment_cache
Definition: character.h:4105
const std::map< bodypart_str_id, bodypart > & get_body() const
Definition: creature.cpp:2167
int get_coverage(bodypart_id bp, item::cover_type cover_type=item::cover_type::COVER_DEFAULT) const
const flag_id flag_PRIMITIVE_RANGED_WEAPON("PRIMITIVE_RANGED_WEAPON")
static const efftype_id effect_drunk("drunk")
static const efftype_id effect_high("high")
static const trait_id trait_TERRIFYING("TERRIFYING")
int ugliness_mandatory
Definition: bodypart.h:305

References bp, effect_drunk, effect_high, Character::enchantment_cache, npc_opinion::fear, flag_PRIMITIVE_RANGED_WEAPON, Creature::get_all_body_parts(), Creature::get_body(), outfit::get_coverage(), Character::get_mutations(), Character::get_painkiller(), get_player_character(), Character::get_stim(), Character::get_wielded_item(), Creature::has_effect(), item::has_flag(), Character::has_flag(), Character::has_trait(), Character::is_armed(), item::is_gun(), json_flag_SAPIOVORE, op_of_u, Character::str_max, trait_TERRIFYING, npc_opinion::trust, body_part_type::ugliness, enchant_vals::UGLINESS, body_part_type::ugliness_mandatory, npc_opinion::value, Character::weapon, Character::weapon_value(), and Character::worn.

Referenced by form_opinion().

◆ get_path_avoid()

std::unordered_set< tripoint > npc::get_path_avoid ( ) const
overridevirtual

Returns a set of points we do not want to path through.

Reimplemented from Character.

Definition at line 3312 of file npc.cpp.

3313 {
3314  std::unordered_set<tripoint> ret;
3315  for( Creature &critter : g->all_creatures() ) {
3316  // TODO: Cache this somewhere
3317  ret.insert( critter.pos() );
3318  }
3319  map &here = get_map();
3321  for( const tripoint &p : here.points_in_radius( pos(), 30 ) ) {
3322  if( here.open_door( *this, p, true, true ) ) {
3323  ret.insert( p );
3324  }
3325  }
3326  }
3328  for( const tripoint &p : here.points_in_radius( pos(), 30 ) ) {
3329  if( doors::can_unlock_door( here, *this, tripoint_bub_ms( p ) ) ) {
3330  ret.insert( p );
3331  }
3332  }
3333  }
3335  for( const tripoint &p : here.points_in_radius( get_player_character().pos(), 1 ) ) {
3336  if( here.close_door( p, true, true ) || here.move_cost( p ) > 2 ) {
3337  ret.insert( p );
3338  }
3339  }
3340  }
3341 
3342  for( const tripoint &p : here.points_in_radius( pos(), 6 ) ) {
3343  if( sees_dangerous_field( p ) || ( here.veh_at( p ).part_with_feature( VPFLAG_CARGO, true ) &&
3344  !move_in_vehicle( const_cast<npc *>( this ), p ) ) ) {
3345  ret.insert( p );
3346  }
3347  }
3348 
3349  return ret;
3350 }
bool close_door(const tripoint &p, bool inside, bool check_only)
Definition: map.cpp:4818
int move_cost(const tripoint &p, const vehicle *ignored_vehicle=nullptr) const
Calculate the cost to move past the tile at p.
Definition: map.cpp:2434
coords::coord_point< tripoint, coords::origin::reality_bubble, coords::ms > tripoint_bub_ms
Definition: coordinates.h:716
bool can_unlock_door(const map &m, const Creature &who, const tripoint_bub_ms &lockp)
Whether a door at "lockp" can be unlocked by "who.".
Definition: gates.cpp:449
@ VPFLAG_CARGO
Definition: veh_type.h:94

References avoid_doors, avoid_locks, doors::can_unlock_door(), map::close_door(), g, get_map(), get_player_character(), npc_follower_rules::has_flag(), hold_the_line, map::move_cost(), Character::move_in_vehicle(), map::open_door(), optional_vpart_position::part_with_feature(), map::points_in_radius(), Creature::pos(), cata::hash64_detail::ret, rules, sees_dangerous_field(), map::veh_at(), and VPFLAG_CARGO.

Referenced by add_fallback_zone(), go_to_omt_destination(), and update_path().

◆ get_pathfinding_settings() [1/2]

const pathfinding_settings & npc::get_pathfinding_settings ( ) const
overridevirtual

Returns settings for pathfinding.

Reimplemented from Character.

Definition at line 3287 of file npc.cpp.

3288 {
3289  return get_pathfinding_settings( false );
3290 }
const pathfinding_settings & get_pathfinding_settings() const override
Returns settings for pathfinding.
Definition: npc.cpp:3287

Referenced by add_fallback_zone(), go_to_omt_destination(), and update_path().

◆ get_pathfinding_settings() [2/2]

const pathfinding_settings & npc::get_pathfinding_settings ( bool  no_bashing) const

Definition at line 3292 of file npc.cpp.

3293 {
3294  path_settings->bash_strength = no_bashing ? 0 : smash_ability();
3295  if( has_trait( trait_NO_BASH ) ) {
3296  path_settings->bash_strength = 0;
3297  }
3298  // TODO: Extract climb skill
3299  const int climb = std::min( 20, get_dex() );
3300  if( climb > 1 ) {
3301  // Success is !one_in(dex), so 0%, 50%, 66%, 75%...
3302  // Penalty for failure chance is 1/success = 1/(1-failure) = 1/(1-(1/dex)) = dex/(dex-1)
3303  path_settings->climb_cost = ( 10 - climb / 5 ) * climb / ( climb - 1 );
3304  } else {
3305  // Climbing at this dexterity will always fail
3306  path_settings->climb_cost = 0;
3307  }
3308 
3309  return *path_settings;
3310 }
int get_dex() const
Definition: character.cpp:4131
static const trait_id trait_NO_BASH("NO_BASH")

References Character::get_dex(), Character::has_trait(), min(), Character::path_settings, smash_ability(), and trait_NO_BASH.

◆ get_previous_attitude()

npc_attitude npc::get_previous_attitude ( )

Definition at line 942 of file npc.cpp.

943 {
944  return previous_attitude;
945 }
npc_attitude previous_attitude
Definition: npc.h:1343

References previous_attitude.

◆ get_previous_mission()

npc_mission npc::get_previous_mission ( ) const

Definition at line 937 of file npc.cpp.

938 {
939  return previous_mission;
940 }
npc_mission previous_mission
Definition: npc.h:1401

References previous_mission.

◆ get_price_rules()

faction_price_rule const * npc::get_price_rules ( item const &  it) const

Definition at line 2109 of file npc.cpp.

2110 {
2111  faction_price_rule const *ret = myclass->get_price_rules( it, *this );
2112  if( ret == nullptr && get_faction() != nullptr ) {
2113  ret = get_faction()->get_price_rules( it, *this );
2114  }
2115  return ret;
2116 }
faction_price_rule const * get_price_rules(item const &it, npc const &guy) const
Definition: faction.cpp:407
faction_price_rule const * get_price_rules(item const &it, npc const &guy) const
Definition: npc_class.cpp:440
faction * get_faction() const override
Definition: npc.cpp:776

References get_faction(), faction::get_price_rules(), npc_class::get_price_rules(), myclass, and cata::hash64_detail::ret.

Referenced by npc_trading::adjusted_price().

◆ get_restock_interval()

std::string npc::get_restock_interval ( ) const

Definition at line 2019 of file npc.cpp.

2020 {
2021  time_duration const restock_remaining =
2023  std::string restock_rem = to_string( restock_remaining );
2024  return restock_rem;
2025 }

References restock, to_string(), and calendar::turn.

Referenced by parse_tags().

◆ get_specified_talk_topic()

std::string const & npc::get_specified_talk_topic ( std::string const &  topic_id)

Definition at line 7189 of file npctalk.cpp.

7190 {
7191  static const dialogue_chatbin default_chatbin;
7192  std::vector<std::pair<std::string const &, std::string const &>> const talk_topics = {
7193  {default_chatbin.first_topic, chatbin.first_topic},
7194  {default_chatbin.talk_radio, chatbin.talk_radio},
7195  {default_chatbin.talk_leader, chatbin.talk_leader},
7196  {default_chatbin.talk_friend, chatbin.talk_friend},
7197  {default_chatbin.talk_stole_item, chatbin.talk_stole_item},
7198  {default_chatbin.talk_wake_up, chatbin.talk_wake_up},
7199  {default_chatbin.talk_mug, chatbin.talk_mug},
7202  {default_chatbin.talk_stranger_wary, chatbin.talk_stranger_wary},
7205  {default_chatbin.talk_friend_guard, chatbin.talk_friend_guard}
7206  };
7207 
7208  const auto iter = std::find_if( talk_topics.begin(), talk_topics.end(),
7209  [&topic_id]( const std::pair<std::string, std::string> &pair ) {
7210  return pair.first == topic_id;
7211  } );
7212  if( iter != talk_topics.end() ) {
7213  return iter->second;
7214  }
7215 
7216  return topic_id;
7217 }
std::string talk_stranger_aggressive
std::string talk_friend
std::string talk_mug
std::string talk_friend_guard
std::string talk_stranger_neutral
std::string talk_leader
std::string first_topic
std::string talk_stranger_friendly
std::string talk_radio
std::string talk_stranger_scared
std::string talk_stranger_wary
std::string talk_wake_up
std::string talk_stole_item

References chatbin, dialogue_chatbin::first_topic, dialogue_chatbin::talk_friend, dialogue_chatbin::talk_friend_guard, dialogue_chatbin::talk_leader, dialogue_chatbin::talk_mug, dialogue_chatbin::talk_radio, dialogue_chatbin::talk_stole_item, dialogue_chatbin::talk_stranger_aggressive, dialogue_chatbin::talk_stranger_friendly, dialogue_chatbin::talk_stranger_neutral, dialogue_chatbin::talk_stranger_scared, dialogue_chatbin::talk_stranger_wary, and dialogue_chatbin::talk_wake_up.

Referenced by dialogue::add_topic().

◆ get_thirst()

int npc::get_thirst ( ) const
overridevirtual

Reimplemented from Character.

Definition at line 3740 of file npc.cpp.

3741 {
3742  return Character::get_thirst() - units::to_milliliter<int>( stomach.get_water() ) / 5;
3743 }
virtual int get_thirst() const
Definition: character.cpp:4517
units::volume get_water() const
Definition: stomach.cpp:447

References Character::get_thirst(), stomach_contents::get_water(), and Character::stomach.

Referenced by address_needs(), complain(), consume_food(), consume_food_from_camp(), decide_needs(), process_turn(), and value().

◆ get_unique_id()

std::string npc::get_unique_id ( ) const

◆ go_to_omt_destination()

void npc::go_to_omt_destination ( )

Definition at line 4945 of file npcmove.cpp.

4946 {
4947  map &here = get_map();
4948  if( ai_cache.guard_pos ) {
4949  if( get_location() == *ai_cache.guard_pos ) {
4950  path.clear();
4951  ai_cache.guard_pos = std::nullopt;
4952  move_pause();
4953  return;
4954  }
4955  }
4956  if( goal == no_goal_point || omt_path.empty() ) {
4957  add_msg_debug( debugmode::DF_NPC, "npc::go_to_destination with no goal" );
4958  move_pause();
4960  return;
4961  }
4962  const tripoint_abs_omt omt_pos = global_omt_location();
4963  if( goal == omt_pos ) {
4964  // We're at our desired map square! Pause to keep the NPC infinite loop counter happy
4965  move_pause();
4967  return;
4968  }
4969  if( !path.empty() ) {
4970  // we already have a path, just use that until we can't.
4971  move_to_next();
4972  return;
4973  }
4974  // get the next path point
4975  if( omt_path.back() == omt_pos ) {
4976  // this should be the square we are at.
4977  omt_path.pop_back();
4978  }
4979  if( !omt_path.empty() ) {
4980  point_rel_omt omt_diff = omt_path.back().xy() - omt_pos.xy();
4981  if( omt_diff.x() > 3 || omt_diff.x() < -3 || omt_diff.y() > 3 || omt_diff.y() < -3 ) {
4982  // we've gone wandering somehow, reset destination.
4983  if( !is_player_ally() ) {
4985  } else {
4986  talk_function::assign_guard( *this );
4987  }
4988  return;
4989  }
4990  }
4991  // TODO: fix point types
4992  tripoint sm_tri =
4993  here.getlocal( project_to<coords::ms>( omt_path.back() ).raw() );
4994  tripoint centre_sub = sm_tri + point( SEEX, SEEY );
4995  if( !here.passable( centre_sub ) ) {
4996  auto candidates = here.points_in_radius( centre_sub, 2 );
4997  for( const tripoint &elem : candidates ) {
4998  if( here.passable( elem ) ) {
4999  centre_sub = elem;
5000  break;
5001  }
5002  }
5003  }
5004  path = here.route( pos(), centre_sub, get_pathfinding_settings(), get_path_avoid() );
5005  add_msg_debug( debugmode::DF_NPC, "%s going %s->%s", get_name(), omt_pos.to_string_writable(),
5007 
5008  if( !path.empty() ) {
5009  move_to_next();
5010  return;
5011  }
5012  move_pause();
5013 }
std::vector< tripoint_abs_omt > omt_path
Definition: character.h:1703
std::string to_string_writable() const
Definition: coordinates.h:124
constexpr auto y() const
Definition: coordinates.h:164
constexpr auto x() const
Definition: coordinates.h:161
std::vector< tripoint > route(const tripoint &f, const tripoint &t, const pathfinding_settings &settings, const std::unordered_set< tripoint > &pre_closed={{ }}) const
Calculate the best path using A*.
void set_omt_destination()
Definition: npcmove.cpp:4851
static constexpr tripoint_abs_omt no_goal_point
Definition: npc.h:1415
void reach_omt_destination()
Definition: npcmove.cpp:4795
std::unordered_set< tripoint > get_path_avoid() const override
Returns a set of points we do not want to path through.
Definition: npc.cpp:3312
constexpr int SEEY
void assign_guard(npc &)

References add_msg_debug, ai_cache, talk_function::assign_guard(), debugmode::DF_NPC, Creature::get_location(), get_map(), Character::get_name(), get_path_avoid(), get_pathfinding_settings(), map::getlocal(), Creature::global_omt_location(), goal, npc_short_term_cache::guard_pos, is_player_ally(), move_pause(), move_to_next(), no_goal_point, Character::omt_path, map::passable(), path, point, map::points_in_radius(), Creature::pos(), reach_omt_destination(), map::route(), SEEX, SEEY, set_omt_destination(), coords::coord_point_base< Point >::to_string_writable(), coords::coord_point_mut< Point, Subpoint, InBounds >::x(), coords::coord_point< Point, Origin, Scale, InBounds >::xy(), and coords::coord_point_mut< Point, Subpoint, InBounds >::y().

Referenced by execute_action().

◆ good_escape_direction()

tripoint npc::good_escape_direction ( bool  include_pos = true)

Definition at line 260 of file npcmove.cpp.

261 {
262  map &here = get_map();
263  // if NPC is repositioning rather than fleeing, they do smarter things
265  "<color_brown>good_escape_direction</color> activated by %s", name );
266 
267  // To do: Eventually careful_retreat should determine if NPC will go to previously identified
268  // safe locations. For now it just sends them to a retreat zone if one exists.
269  bool careful_retreat = mem_combat.repositioning || mem_combat.panic == 0;
270  if( !careful_retreat ) {
271  careful_retreat = mem_combat.panic < 10 + personality.bravery + get_int();
272  if( !careful_retreat ) {
273  add_msg_debug( debugmode::DF_NPC_MOVEAI, "%s is panicking too much to use retreat zones and stuff.",
274  name );
275  } else {
276  add_msg_debug( debugmode::DF_NPC_MOVEAI, "%s is running away but still being smart about it.",
277  name );
278  }
279  }
280  //if not, consider regrouping on the player if they're getting far away.
281  //in the future this should run to the strongest nearby ally, remembered in mem_combat or cached.
282  bool run_to_friend = mem_combat.repositioning || mem_combat.panic == 0;
283  if( !run_to_friend ) {
284  run_to_friend = mem_combat.panic < 10 + personality.bravery + op_of_u.trust;
285  }
286  if( path.empty() && careful_retreat ) {
288  "%s doesn't already have an escape path. Checking for retreat zone.", name );
289  zone_type_id retreat_zone = zone_type_NPC_RETREAT;
290  const tripoint_abs_ms abs_pos = get_location();
292  std::optional<tripoint_abs_ms> retreat_target = mgr.get_nearest( retreat_zone, abs_pos, 60,
293  fac_id );
294  // if there is a retreat zone in range, go there
295 
296 
297  if( retreat_target && *retreat_target != abs_pos ) {
299  "<color_light_gray>%s is </color><color_brown>repositioning</color> to %i %i %i", name,
300  here.getlocal( *retreat_target ).x, here.getlocal( *retreat_target ).y,
301  here.getlocal( *retreat_target ).z );
302  update_path( here.getlocal( *retreat_target ) );
303  }
304  if( !path.empty() ) {
305  return path[0];
306  } else {
308  "<color_light_gray>%s did not detect a zone to reposition to, or is too panicked. Checking to see if there's an ally.</color>",
309  name );
310  }
311  } else if( path.empty() && run_to_friend && is_player_ally() ) {
312  Character &player_character = get_player_character();
313  int dist = rl_dist( pos(), player_character.pos() );
314  int def_radius = rules.has_flag( ally_rule::follow_close ) ? follow_distance() : 6;
315  if( dist > def_radius ) {
317  "<color_light_gray>%s is repositioning closer to</color> you", name );
318  tripoint_bub_ms destination = get_player_character().pos_bub();
319  int loop_avoider = 0;
320  while( !can_move_to( destination.raw() ) && loop_avoider < 10 ) {
321  destination.x() += rng( -2, 2 );
322  destination.y() += rng( -2, 2 );
323  loop_avoider += 1;
324  }
325  update_path( destination.raw() );
326  if( loop_avoider == 10 ) {
328  "<color_red>%s had to break out of an infinite loop when looking for a good escape destination</color>. This might not be that big a deal but if you're seeing this a lot, there might be something wrong in good_escape_direction().",
329  name );
330  }
331  }
332  } else {
334  "<color_light_gray>%s couldn't find anywhere preset to reposition to. Looking for a random location.</color>",
335  name );
336  }
337 
338 
339  std::vector<tripoint> candidates;
340 
341  const auto rate_pt = [&]( const tripoint & pt, const float threat_val ) {
342  if( !can_move_to( pt, !rules.has_flag( ally_rule::allow_bash ) ) ) {
344  "<color_dark_gray>%s can't move to %i, %i, %i. Rate_pt returning absurdly high rating.</color>",
345  name, pt.x, pt.y, pt.z );
346  return MAX_FLOAT;
347  }
348  float rating = threat_val;
349  for( const auto &e : here.field_at( pt ) ) {
350  if( is_dangerous_field( e.second ) ) {
351  // Note, field danger should be rated more specifically than this,
352  // to distinguish eg fire vs smoke. Probably needs to be handled by field code, not here.
354  "<color_dark_gray>%s spotted field %s at %i, %i, %i; adding %f to rating</color>", name,
355  e.second.name(), pt.x, pt.y, pt.z, e.second.get_field_intensity() );
356  rating += e.second.get_field_intensity();
357  }
358  }
359  return rating;
360  };
361 
362  float best_rating = include_pos ? rate_pt( pos(), 0.0f ) : FLT_MAX;
363  candidates.emplace_back( pos() );
364 
365  std::map<direction, float> adj_map;
366  int num_points_searched = 1;
367  for( direction pt_dir : npc_threat_dir ) {
368  const tripoint pt = pos() + displace_XY( pt_dir );
369  float cur_rating = rate_pt( pt, ai_cache.threat_map[ pt_dir ] );
370  adj_map[pt_dir] = cur_rating;
371  if( cur_rating == best_rating ) {
373  "<color_light_gray>%s thinks </color><color_light_blue>%i, %i, %i</color><color_light_gray> is the best retreat spot they've seen so far</color><color_light_blue> rated %1.2f</color><color_light_gray>after checking %i candidates</color>",
374  name, pt.x, pt.y, pt.z, best_rating, num_points_searched );
375  candidates.emplace_back( pos() + displace_XY( pt_dir ) );
376  } else if( cur_rating < best_rating ) {
377  if( one_in( 5 ) ) {
379  "<color_dark_gray>%s just wants to let you know, esteemed debugger, that they're still checking escape points but haven't found any new good ones. Checked %i.</color>",
380  name, num_points_searched );
381  }
382  candidates.clear();
383  candidates.emplace_back( pos() + displace_XY( pt_dir ) );
384  best_rating = cur_rating;
385  }
386  num_points_searched += 1;
387  }
388  ( void )num_points_searched;
389  tripoint redirect_goal = random_entry( candidates );
390  add_msg_debug( debugmode::DF_NPC_MOVEAI, "%s is repositioning to %i, %i, %i", name, redirect_goal.x,
391  redirect_goal.y, redirect_goal.z );
392  return redirect_goal;
393 }
int get_int() const
Definition: character.cpp:4139
static zone_manager & get_manager()
Definition: clzones.h:550
std::optional< tripoint_abs_ms > get_nearest(const zone_type_id &type, const tripoint_abs_ms &where, int range=MAX_DISTANCE, const faction_id &fac=your_fac) const
Definition: clzones.cpp:1164
point displace_XY(const direction dir)
Definition: line.cpp:515
@ DF_NPC_MOVEAI
Definition: debug.h:270
static constexpr float MAX_FLOAT
Definition: npcmove.cpp:155
static const zone_type_id zone_type_NPC_RETREAT("NPC_RETREAT")
V random_entry(const C &container, D default_value)
Returns a random entry in the container.
Definition: rng.h:104
int y
Definition: point.h:133
int x
Definition: point.h:132

References add_msg_debug, ai_cache, allow_bash, npc_personality::bravery, can_move_to(), debugmode::DF_NPC_MOVEAI, displace_XY(), Character::fac_id, map::field_at(), follow_close, follow_distance(), Character::get_int(), Creature::get_location(), zone_manager::get_manager(), get_map(), zone_manager::get_nearest(), get_player_character(), map::getlocal(), npc_follower_rules::has_flag(), Creature::is_dangerous_field(), is_player_ally(), MAX_FLOAT, mem_combat, Character::name, npc_threat_dir, one_in(), op_of_u, npc_combat_memory_cache::panic, path, personality, Creature::pos(), Creature::pos_bub(), random_entry(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), npc_combat_memory_cache::repositioning, rl_dist(), rng(), rules, npc_short_term_cache::threat_map, npc_opinion::trust, update_path(), coords::coord_point_mut< Point, Subpoint, InBounds >::x(), tripoint::x, coords::coord_point_mut< Point, Subpoint, InBounds >::y(), tripoint::y, tripoint::z, and zone_type_NPC_RETREAT.

Referenced by execute_action(), and move().

◆ guaranteed_hostile()

bool npc::guaranteed_hostile ( ) const

Is enemy or will turn into one (can't be convinced not to attack).

Definition at line 2312 of file npc.cpp.

2313 {
2314  return is_enemy() || ( my_fac && my_fac->likes_u < -10 );
2315 }

References is_enemy(), faction_template::likes_u, and Character::my_fac.

Referenced by anonymous_namespace{math_parser_diag.cpp}::_friend_match_filter_character(), basic_symbol_color(), target_ui::confirm_non_enemy_target(), extended_description(), move(), and on_attacked().

◆ guard_current_pos()

void npc::guard_current_pos ( )

Definition at line 5015 of file npcmove.cpp.

5016 {
5018  guard_pos = get_location();
5019 }

References Creature::get_location(), Creature::global_omt_location(), goal, and guard_pos.

Referenced by set_omt_destination().

◆ handle_sound()

void npc::handle_sound ( sounds::sound_t  priority,
const std::string &  description,
int  heard_volume,
const tripoint spos 
)

Definition at line 1256 of file npctalk.cpp.

1258 {
1259  const map &here = get_map();
1260  const tripoint_abs_ms s_abs_pos = here.getglobal( spos );
1261  const tripoint_abs_ms my_abs_pos = get_location();
1262 
1264  "%s heard '%s', priority %d at volume %d from %d:%d, my pos %d:%d",
1265  disp_name(), description, static_cast<int>( spriority ), heard_volume,
1266  s_abs_pos.x(), s_abs_pos.y(), my_abs_pos.x(), my_abs_pos.y() );
1267 
1268  Character &player_character = get_player_character();
1269  bool player_ally = player_character.pos() == spos && is_player_ally();
1270  Character *const sound_source = get_creature_tracker().creature_at<Character>( spos );
1271  bool npc_ally = sound_source && sound_source->is_npc() && is_ally( *sound_source );
1272 
1273  if( ( player_ally || npc_ally ) && spriority == sounds::sound_t::order ) {
1274  say( chat_snippets().snip_acknowledged.translated() );
1275  }
1276 
1277  if( sees( spos ) || is_hallucination() ) {
1278  return;
1279  }
1280  // ignore low priority sounds if the NPC "knows" it came from a friend.
1281  // TODO: NPC will need to respond to talking noise eventually
1282  // but only for bantering purposes, not for investigating.
1283  if( spriority < sounds::sound_t::alarm ) {
1284  if( player_ally ) {
1285  add_msg_debug( debugmode::DF_NPC, "Allied NPC ignored same faction %s", get_name() );
1286  return;
1287  }
1288  if( npc_ally ) {
1289  add_msg_debug( debugmode::DF_NPC, "NPC ignored same faction %s", get_name() );
1290  return;
1291  }
1292  }
1293  // discount if sound source is player, or seen by player,
1294  // and listener is friendly and sound source is combat or alert only.
1295  if( spriority < sounds::sound_t::alarm && player_character.sees( spos ) ) {
1296  if( is_player_ally() ) {
1297  add_msg_debug( debugmode::DF_NPC, "NPC %s ignored low priority noise that player can see",
1298  get_name() );
1299  return;
1300  // discount if sound source is player, or seen by player,
1301  // listener is neutral and sound type is worth investigating.
1302  } else if( spriority < sounds::sound_t::destructive_activity &&
1304  return;
1305  }
1306  }
1307  // patrolling guards will investigate more readily than stationary NPCS
1308  int investigate_dist = 10;
1310  investigate_dist = 50;
1311  }
1313  investigate_dist = 0;
1314  }
1315  if( ai_cache.total_danger < 1.0f ) {
1316  if( spriority == sounds::sound_t::movement && !in_vehicle ) {
1317  warn_about( "movement_noise", rng( 1, 10 ) * 1_minutes, description );
1318  } else if( spriority > sounds::sound_t::movement ) {
1319  if( ( spriority == sounds::sound_t::speech || spriority == sounds::sound_t::alert ||
1320  spriority == sounds::sound_t::order ) && sound_source &&
1322  warn_about( "speech_noise", rng( 1, 10 ) * 1_minutes );
1323  } else if( spriority > sounds::sound_t::activity ) {
1324  warn_about( "combat_noise", rng( 1, 10 ) * 1_minutes );
1325  }
1326  bool should_check = rl_dist( pos(), spos ) < investigate_dist;
1327  if( should_check ) {
1328  const zone_manager &mgr = zone_manager::get_manager();
1329  // NOLINTNEXTLINE(bugprone-branch-clone)
1330  if( mgr.has( zone_type_NPC_NO_INVESTIGATE, s_abs_pos, fac_id ) ) {
1331  should_check = false;
1332  } else if( mgr.has( zone_type_NPC_INVESTIGATE_ONLY, my_abs_pos, fac_id ) &&
1333  !mgr.has( zone_type_NPC_INVESTIGATE_ONLY, s_abs_pos, fac_id ) ) {
1334  should_check = false;
1335  }
1336  }
1337  if( should_check ) {
1338  add_msg_debug( debugmode::DF_NPC, "%s added noise at pos %d:%d", get_name(),
1339  s_abs_pos.x(), s_abs_pos.y() );
1340  dangerous_sound temp_sound;
1341  // TODO: fix point types
1342  temp_sound.abs_pos = s_abs_pos.raw();
1343  temp_sound.volume = heard_volume;
1344  temp_sound.type = spriority;
1345  if( !ai_cache.sound_alerts.empty() ) {
1346  // TODO: fix point types
1347  if( ai_cache.sound_alerts.back().abs_pos != s_abs_pos.raw() ) {
1348  ai_cache.sound_alerts.push_back( temp_sound );
1349  }
1350  } else {
1351  ai_cache.sound_alerts.push_back( temp_sound );
1352  }
1353  }
1354  }
1355  }
1356 }
npc_attitude get_attitude() const override
Definition: npc.cpp:3546
bool is_ally(const Character &p) const override
Definition: npc.cpp:2260
attitude_group get_attitude_group(npc_attitude att) const
Definition: npc.cpp:3495
bool has(const zone_type_id &type, const tripoint_abs_ms &where, const faction_id &fac=your_fac) const
Definition: clzones.cpp:1003
@ knows_your_voice
Definition: faction.h:56
static const zone_type_id zone_type_NPC_NO_INVESTIGATE("NPC_NO_INVESTIGATE")
static const zone_type_id zone_type_NPC_INVESTIGATE_ONLY("NPC_INVESTIGATE_ONLY")
int volume
Definition: npc.h:541
tripoint abs_pos
Definition: npc.h:539
sounds::sound_t type
Definition: npc.h:540
std::vector< dangerous_sound > sound_alerts
Definition: npc.h:572

References dangerous_sound::abs_pos, sounds::activity, add_msg_debug, ai_cache, sounds::alarm, sounds::alert, chat_snippets(), creature_tracker::creature_at(), sounds::destructive_activity, debugmode::DF_NPC, Character::disp_name(), Character::fac_id, get_attitude(), get_attitude_group(), get_creature_tracker(), Creature::get_location(), zone_manager::get_manager(), get_map(), Character::get_name(), get_player_character(), map::getglobal(), zone_manager::has(), has_faction_relationship(), npc_follower_rules::has_flag(), hostile, ignore_noise, Character::in_vehicle, is_ally(), is_hallucination(), Character::is_npc(), is_player_ally(), npc_factions::knows_your_voice, sounds::movement, NPC_MISSION_GUARD_ALLY, NPC_MISSION_GUARD_PATROL, sounds::order, Creature::pos(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), rl_dist(), rng(), rules, say(), Character::sees(), npc_short_term_cache::sound_alerts, sounds::speech, npc_short_term_cache::total_danger, dangerous_sound::type, dangerous_sound::volume, warn_about(), coords::coord_point_mut< Point, Subpoint, InBounds >::x(), coords::coord_point_mut< Point, Subpoint, InBounds >::y(), zone_type_NPC_INVESTIGATE_ONLY, and zone_type_NPC_NO_INVESTIGATE.

Referenced by sounds::process_sound_markers().

◆ has_activity()

bool npc::has_activity ( ) const

Definition at line 3541 of file npc.cpp.

3542 {
3544 }

References attitude, NPC_MISSION_ACTIVITY, and NPCATT_ACTIVITY.

Referenced by talker_npc::get_topics().

◆ has_companion_mission()

bool npc::has_companion_mission ( ) const

◆ has_faction_relationship()

bool npc::has_faction_relationship ( const Character you,
npc_factions::relationship  flag 
) const

Definition at line 2249 of file npc.cpp.

2251 {
2252  faction *p_fac = you.get_faction();
2253  if( !my_fac || !p_fac ) {
2254  return false;
2255  }
2256 
2257  return my_fac->has_relationship( p_fac->id, flag );
2258 }
faction_id id
Definition: faction.h:112
bool has_relationship(const faction_id &guy_id, npc_factions::relationship flag) const
Definition: faction.cpp:419

References Character::get_faction(), faction::has_relationship(), faction_template::id, and Character::my_fac.

Referenced by assess_danger(), attitude_to(), handle_sound(), and would_take_that().

◆ has_healing_item()

bool npc::has_healing_item ( healing_options  try_to_fix)

Definition at line 2146 of file npc.cpp.

2147 {
2148  return !get_healing_item( try_to_fix, true ).is_null();
2149 }
item & get_healing_item(healing_options try_to_fix, bool first_best=false)
Definition: npc.cpp:2200

References get_healing_item(), and item::is_null().

◆ has_healing_options() [1/2]

healing_options npc::has_healing_options ( )

Definition at line 2151 of file npc.cpp.

2152 {
2153  healing_options try_to_fix;
2154  try_to_fix.set_all();
2155  return has_healing_options( try_to_fix );
2156 }
void set_all()
Definition: npc.cpp:2137

References healing_options::set_all().

Referenced by address_needs().

◆ has_healing_options() [2/2]

healing_options npc::has_healing_options ( healing_options  try_to_fix)

Definition at line 2158 of file npc.cpp.

2159 {
2160  healing_options can_fix;
2161  can_fix.clear_all();
2162  healing_options *fix_p = &can_fix;
2163 
2164  visit_items( [&fix_p, try_to_fix]( item * node, item * ) {
2165  const use_function *use = node->type->get_use( "heal" );
2166  if( use == nullptr ) {
2167  return VisitResponse::NEXT;
2168  }
2169 
2170  const heal_actor &actor = dynamic_cast<const heal_actor &>( *use->get_actor_ptr() );
2171  if( try_to_fix.bandage && !fix_p->bandage && actor.bandages_power > 0.0f ) {
2172  fix_p->bandage = true;
2173  }
2174  if( try_to_fix.disinfect && !fix_p->disinfect && actor.disinfectant_power > 0.0f ) {
2175  fix_p->disinfect = true;
2176  }
2177  if( try_to_fix.bleed && !fix_p->bleed && actor.bleed > 0 ) {
2178  fix_p->bleed = true;
2179  }
2180  if( try_to_fix.bite && !fix_p->bite && actor.bite > 0 ) {
2181  fix_p->bite = true;
2182  }
2183  if( try_to_fix.infect && !fix_p->infect && actor.infect > 0 ) {
2184  fix_p->infect = true;
2185  }
2186  // if we've found items for everything we're looking for, we're done
2187  if( ( !try_to_fix.bandage || fix_p->bandage ) &&
2188  ( !try_to_fix.disinfect || fix_p->disinfect ) &&
2189  ( !try_to_fix.bleed || fix_p->bleed ) &&
2190  ( !try_to_fix.bite || fix_p->bite ) &&
2191  ( !try_to_fix.infect || fix_p->infect ) ) {
2192  return VisitResponse::ABORT;
2193  }
2194 
2195  return VisitResponse::NEXT;
2196  } );
2197  return can_fix;
2198 }
void clear_all()
Definition: npc.cpp:2118

References ABORT, healing_options::bandage, heal_actor::bandages_power, heal_actor::bite, healing_options::bite, heal_actor::bleed, healing_options::bleed, healing_options::clear_all(), healing_options::disinfect, heal_actor::disinfectant_power, itype::get_use(), heal_actor::infect, healing_options::infect, NEXT, item::type, Character::use(), and Character::visit_items().

◆ has_identified()

bool npc::has_identified ( const itype_id item_id) const
inlineoverridevirtual

Note that we've read a book at least once.

Implements Character.

Definition at line 986 of file npc.h.

986  {
987  return true;
988  }

◆ has_item_whitelist()

bool npc::has_item_whitelist ( ) const

Definition at line 7219 of file npctalk.cpp.

7220 {
7221  return is_player_ally() && !rules.pickup_whitelist->empty();
7222 }
pimpl< auto_pickup::npc_settings > pickup_whitelist
Definition: npc.h:514

References is_player_ally(), npc_follower_rules::pickup_whitelist, and rules.

Referenced by find_item(), item_name_whitelisted(), item_whitelisted(), and wants_take_that().

◆ has_job()

bool npc::has_job ( ) const
inline

Definition at line 1316 of file npc.h.

1316  {
1317  return job.has_job();
1318  }
bool has_job() const
Definition: npc.cpp:183

References job_data::has_job(), and job.

Referenced by faction_display(), basecamp::job_assignment_ui(), and move().

◆ has_omt_destination()

bool npc::has_omt_destination ( ) const

Definition at line 4790 of file npcmove.cpp.

4791 {
4792  return goal != no_goal_point;
4793 }

References goal, and no_goal_point.

Referenced by address_player(), and long_term_goal_action().

◆ has_painkiller()

bool npc::has_painkiller ( )

Definition at line 2227 of file npc.cpp.

2228 {
2229  return inv->has_enough_painkiller( get_pain() );
2230 }
pimpl< inventory > inv
Definition: character.h:2712

References Creature::get_pain(), and Character::inv.

Referenced by address_needs().

◆ has_player_activity()

bool npc::has_player_activity ( ) const

◆ heal_player()

void npc::heal_player ( Character patient)

Definition at line 4328 of file npcmove.cpp.

4329 {
4330  // Avoid more than one first aid activity at a time.
4332  return;
4333  }
4334 
4335  int dist = rl_dist( pos(), patient.pos() );
4336 
4337  if( dist > 1 ) {
4338  // We need to move to the player
4339  update_path( patient.pos() );
4340  move_to_next();
4341  return;
4342  }
4343 
4344  viewer &player_view = get_player_view();
4345  // Close enough to heal!
4346  bool u_see = player_view.sees( *this ) || player_view.sees( patient );
4347  if( u_see ) {
4348  add_msg( _( "%1$s starts healing %2$s." ), disp_name(), patient.disp_name() );
4349  }
4350 
4352  if( used.is_null() ) {
4353  debugmsg( "%s tried to heal you but has no healing item", disp_name() );
4354  return;
4355  }
4356  if( !is_hallucination() ) {
4357  int charges_used = used.type->invoke( this, used, patient.pos(), "heal" ).value_or( 0 );
4358  consume_charges( used, charges_used );
4359  } else {
4360  pretend_heal( patient, used );
4361  }
4362 
4363 }
bool consume_charges(item &used, int qty)
Consume charges of a tool or comestible item, potentially destroying it in the process.
Definition: character.cpp:7239
bool has_activity(const activity_id &type) const
Check if player currently has a given activity.
Definition: character.cpp:8973
void pretend_heal(Character &patient, item used)
Definition: npcmove.cpp:4365
Definition: viewer.h:11
virtual bool sees(const tripoint &target, bool is_avatar=false, int range_mod=0) const =0
static const activity_id ACT_FIRSTAID("ACT_FIRSTAID")

References _, ACT_FIRSTAID, add_msg(), ai_cache, npc_short_term_cache::can_heal, Character::consume_charges(), debugmsg, Character::disp_name(), get_healing_item(), get_player_view(), Character::has_activity(), itype::invoke(), is_hallucination(), item::is_null(), move_to_next(), Creature::pos(), pretend_heal(), rl_dist(), viewer::sees(), item::type, and update_path().

Referenced by execute_action().

◆ heal_self()

void npc::heal_self ( )

Definition at line 4374 of file npcmove.cpp.

4375 {
4376  if( has_effect( effect_asthma ) ) {
4377  item *treatment = nullptr;
4378  std::string iusage = "INHALER";
4379 
4380  const auto filter_use = [this]( const std::string & filter ) -> std::vector<item *> {
4381  auto inv_filtered = items_with( [&filter]( const item & itm )
4382  {
4383  return ( itm.type->get_use( filter ) != nullptr ) && itm.ammo_sufficient( nullptr );
4384  } );
4385  return inv_filtered;
4386  };
4387 
4388  const auto inv_inhalers = filter_use( iusage );
4389  if( !inv_inhalers.empty() ) {
4390  treatment = inv_inhalers.front();
4391  } else {
4392  iusage = "OXYGEN_BOTTLE";
4393  const auto inv_oxybottles = filter_use( iusage );
4394  if( !inv_oxybottles.empty() ) {
4395  treatment = inv_oxybottles.front();
4396  }
4397  }
4398  if( treatment != nullptr ) {
4399  treatment->get_use( iusage )->call( this, *treatment, pos() );
4400  treatment->ammo_consume( treatment->ammo_required(), pos(), this );
4401  return;
4402  }
4403  }
4404 
4405  // Avoid more than one first aid activity at a time.
4407  return;
4408  }
4409 
4411  if( used.is_null() ) {
4412  debugmsg( "%s tried to heal self but has no healing item", disp_name() );
4413  return;
4414  }
4415 
4416  add_msg_if_player_sees( *this, _( "%1$s starts applying a %2$s." ), disp_name(), used.tname() );
4417  warn_about( "heal_self", 1_turns );
4418 
4419  int charges_used = used.type->invoke( this, used, pos(), "heal" ).value_or( 0 );
4420  if( used.is_medication() && charges_used > 0 ) {
4421  consume_charges( used, charges_used );
4422  }
4423 }
int ammo_consume(int qty, const tripoint &pos, Character *carrier)
Consume ammo (if available) and return the amount of ammo that was consumed Consume order: loaded ite...
Definition: item.cpp:10878
int ammo_required() const
Quantity of ammunition consumed per usage of tool or with each shot of gun.
Definition: item.cpp:10821
bool is_medication() const
Definition: item.cpp:9489
bool ammo_sufficient(const Character *carrier, int qty=1) const
Check if sufficient ammo is loaded for given number of uses.
Definition: item.cpp:10855
static const efftype_id effect_asthma("asthma")
std::optional< int > call(Character *, item &, const tripoint &) const
Definition: iuse.cpp:8922

References _, ACT_FIRSTAID, add_msg_if_player_sees(), ai_cache, item::ammo_consume(), item::ammo_required(), item::ammo_sufficient(), use_function::call(), npc_short_term_cache::can_heal, Character::consume_charges(), debugmsg, Character::disp_name(), effect_asthma, filter, get_healing_item(), itype::get_use(), item::get_use(), Character::has_activity(), Creature::has_effect(), itype::invoke(), item::is_medication(), item::is_null(), visitable::items_with(), Creature::pos(), item::tname(), item::type, and warn_about().

Referenced by execute_action().

◆ hostile_anger_level()

int npc::hostile_anger_level ( ) const

Definition at line 1621 of file npc.cpp.

1622 {
1623  return 20 + op_of_u.fear - personality.aggression;
1624 }

References npc_personality::aggression, npc_opinion::fear, op_of_u, and personality.

Referenced by talker_npc::check_hostile_response(), and turned_hostile().

◆ hp_description()

std::pair< std::string, nc_color > npc::hp_description ( ) const

Definition at line 3417 of file npc.cpp.

3418 {
3419  int cur_hp = hp_percentage();
3420  std::string damage_info;
3421  std::string pronoun;
3422  if( male ) {
3423  pronoun = _( "He " );
3424  } else {
3425  pronoun = _( "She " );
3426  }
3427  nc_color col;
3428  if( cur_hp == 100 ) {
3429  damage_info = pronoun + _( "is uninjured." );
3430  col = c_green;
3431  } else if( cur_hp >= 80 ) {
3432  damage_info = pronoun + _( "is lightly injured." );
3433  col = c_light_green;
3434  } else if( cur_hp >= 60 ) {
3435  damage_info = pronoun + _( "is moderately injured." );
3436  col = c_yellow;
3437  } else if( cur_hp >= 30 ) {
3438  damage_info = pronoun + _( "is heavily injured." );
3439  col = c_yellow;
3440  } else if( cur_hp >= 10 ) {
3441  damage_info = pronoun + _( "is severely injured." );
3442  col = c_light_red;
3443  } else {
3444  damage_info = pronoun + _( "is nearly dead!" );
3445  col = c_red;
3446  }
3447  return std::make_pair( damage_info, col );
3448 }
#define c_yellow
Definition: color.h:30

References _, c_green, c_light_green, c_light_red, c_red, c_yellow, Character::hp_percentage(), and Character::male.

Referenced by faction_display().

◆ identify()

void npc::identify ( const item )
inlineoverridevirtual

Implements Character.

Definition at line 989 of file npc.h.

989  {
990  // Do nothing
991  }

◆ import_and_clean() [1/2]

void npc::import_and_clean ( const cata_path path)

Read json and apply post-import cleanup.

Definition at line 1734 of file savegame.cpp.

1735 {
1736  std::ifstream fin( path.get_unrelative_path(), std::ios::binary );
1737  size_t json_offset = chkversion( fin );
1738  JsonValue jsin = json_loader::from_path_at_offset( path, json_offset );
1739  import_and_clean( jsin.get_object() );
1740 }
JsonObject get_object() const
static JsonValue from_path_at_offset(const cata_path &source_file, size_t offset=0) noexcept(false)
void import_and_clean(const cata_path &path)
Read json and apply post-import cleanup.
Definition: savegame.cpp:1734
static size_t chkversion(std::istream &fin)
Definition: savegame.cpp:185

References chkversion(), json_loader::from_path_at_offset(), JsonValue::get_object(), and path.

◆ import_and_clean() [2/2]

void npc::import_and_clean ( const JsonObject data)
private

Definition at line 1742 of file savegame.cpp.

1743 {
1744  deserialize( data );
1745 
1746  npc defaults; // to avoid hardcoding defaults here
1747 
1748  // avoid duplicate id
1749  setID( g->assign_npc_id(), /* force */ true );
1750 
1751  // timestamps are irrelevant if importing into a different world
1752  last_updated = defaults.last_updated;
1753  lifespan_end = defaults.lifespan_end;
1754  effects->clear();
1758 
1759  // space coordinates are irrelevant if importing into a different world
1760  set_location( defaults.get_location() );
1761  omt_path = defaults.omt_path;
1762  known_traps.clear();
1763  camps = defaults.camps;
1765  guard_pos = defaults.guard_pos;
1766  pulp_location = defaults.pulp_location;
1767  chair_pos = defaults.chair_pos;
1768  wander_pos = defaults.wander_pos;
1769  goal = defaults.goal;
1770  assigned_camp = defaults.assigned_camp;
1771  job = defaults.job;
1772 
1773  // mission related
1774  mission = defaults.mission;
1782  chatbin.missions.clear();
1783  chatbin.missions_assigned.clear();
1784  chatbin.mission_selected = nullptr;
1785 
1786  // activity related
1787  activity = defaults.activity;
1788  backlog = defaults.backlog;
1794 
1795  // miscellaneous
1796  in_vehicle = defaults.in_vehicle;
1797  warning_record = defaults.warning_record;
1798  complaints = defaults.complaints;
1799  unique_id = defaults.unique_id;
1800 }
queued_eocs queued_effect_on_conditions
Definition: character.h:2770
void clear_destination()
std::list< consumption_event > consumption_history
Definition: character.h:2730
player_activity stashed_outbounds_backlog
Definition: character.h:2708
void setID(character_id i, bool force=false)
sets the ID, will only succeed when the current id is not valid allows forcing a -1 id which is requi...
Definition: character.cpp:641
int activity_vehicle_part_index
Definition: character.h:2804
time_point last_sleep_check
last time we checked for sleep
Definition: character.h:3901
player_activity stashed_outbounds_activity
Definition: character.h:2707
trap_map known_traps
Definition: character.h:3897
std::map< faction_id, std::pair< int, time_point > > warning_record
warnings from a faction about bad behavior
Definition: character.h:3903
void set_location(const tripoint_abs_ms &loc)
Definition: creature.cpp:207
pimpl< effects_map > effects
Definition: creature.h:1204
void clear()
Definition: inventory.cpp:251
std::string companion_mission_role_id
Definition: npc.h:1393
npc_mission mission
Definition: npc.h:1400
void deserialize(const JsonObject &data) override
inventory companion_mission_inv
Definition: npc.h:1399
std::optional< tripoint_abs_ms > chair_pos
Definition: npc.h:1373
std::vector< tripoint_abs_omt > companion_mission_points
Definition: npc.h:1395
void reset_companion_mission()
Unset a companion mission. Precondition: !has_companion_mission()
Definition: npc.cpp:3466
std::optional< tripoint_abs_ms > wander_pos
Definition: npc.h:1381
mission * mission_selected
The mission (if any) that we talk about right now.
std::vector< mission * > missions
Missions that the talker can give out.

References Character::activity, Character::activity_vehicle_part_index, assigned_camp, Character::backlog, Character::camps, chair_pos, chatbin, inventory::clear(), Character::clear_destination(), companion_mission_inv, companion_mission_points, companion_mission_role_id, companion_mission_time, companion_mission_time_ret, complaints, Character::consumption_history, current_activity_id, deserialize(), Creature::effects, g, Creature::get_location(), goal, guard_pos, Character::in_vehicle, job, Character::known_traps, last_player_seen_pos, Character::last_sleep_check, Creature::last_updated, Creature::lifespan_end, mission, dialogue_chatbin::mission_selected, dialogue_chatbin::missions, dialogue_chatbin::missions_assigned, Character::omt_path, previous_mission, pulp_location, Character::queued_effect_on_conditions, reset_companion_mission(), Creature::set_location(), Character::setID(), Character::stashed_outbounds_activity, Character::stashed_outbounds_backlog, unique_id, wander_pos, and Character::warning_record.

◆ indoor_voice()

int npc::indoor_voice ( ) const

Definition at line 1768 of file npc.cpp.

1769 {
1770  const int max_volume = get_shout_volume();
1771  const int min_volume = 1;
1772  // Actual hearing distance is incredibly dependent on ambient noise and our noise propagation model is... rather binary
1773  // But we'll assume people normally want to project their voice about 6 meters away.
1774  int wanted_volume = 6;
1776  const int distance_to_player = rl_dist( pos(), player.pos() );
1777  if( is_following() || is_ally( player ) ) {
1778  wanted_volume = distance_to_player;
1779  } else if( is_enemy() && sees( player.pos() ) ) {
1780  // Battle cry! Bandits have no concept of indoor voice, even when not threatened.
1781  wanted_volume = max_volume;
1782  }
1783  // Possible fallthrough: neutral or unaware enemy NPCs talk at default wanted_volume
1784 
1785  // Don't wake up friends when using our indoor voice
1786  for( const auto &bunk_buddy : get_cached_friends() ) {
1787  Character *char_buddy = nullptr;
1788  if( auto buddy = bunk_buddy.lock() ) {
1789  char_buddy = dynamic_cast<Character *>( buddy.get() );
1790  }
1791  if( !char_buddy ) {
1792  continue;
1793  }
1794  if( char_buddy->has_effect( effect_sleep ) ) {
1795  int distance_to_sleeper = rl_dist( pos(), char_buddy->pos() );
1796  if( wanted_volume >= distance_to_sleeper ) {
1797  // Speak just quietly enough to not disturb anyone
1798  wanted_volume = distance_to_sleeper - 1;
1799  }
1800  }
1801  }
1802 
1803  return std::clamp( wanted_volume, min_volume, max_volume );
1804 }
constexpr T clamp(const T &val, const T &min, const T &max)
Clamp first argument so that it is no lower than second and no higher than third.
Definition: cata_utility.h:221
int get_shout_volume() const
Definition: character.cpp:7413
const std::vector< weak_ptr_fast< Creature > > & get_cached_friends() const
Definition: npc.cpp:2954
static const efftype_id effect_sleep("sleep")

References clamp(), effect_sleep, get_cached_friends(), get_player_character(), Character::get_shout_volume(), Creature::has_effect(), is_ally(), is_enemy(), is_following(), player, Creature::pos(), rl_dist(), and Character::sees().

Referenced by say().

◆ invalidate_range_cache()

void npc::invalidate_range_cache ( )

Definition at line 1383 of file npc.cpp.

1384 {
1386 
1387  if( !weapon ) {
1389  } else if( weapon->is_gun() ) {
1392  } else {
1394  }
1395 }
int most_accurate_aiming_method_limit(const item &gun) const
Definition: character.cpp:1017
int reach_range(const Character &guy) const
Definition: item.cpp:7509
int confident_shoot_range(const item &it, int at_recoil) const
Definition: npcmove.cpp:2674

References confident_range_cache, confident_shoot_range(), Character::get_wielded_item(), item::is_gun(), Character::most_accurate_aiming_method_limit(), item::reach_range(), and Character::weapon.

Referenced by assess_danger(), talker_npc::clear_ai_rule(), move(), talker_npc::set_ai_rule(), talker_npc::toggle_ai_rule(), and wield().

◆ invoke_item() [1/7]

bool Character::invoke_item

As above two, but with position equal to current position.

Definition at line 1928 of file character.cpp.

7145 {
7146  return invoke_item( used, pos() );
7147 }
virtual bool invoke_item(item *, const tripoint &pt, int pre_obtain_moves=-1)
Asks how to use the item (if it has more than one use_method) and uses it.
Definition: character.cpp:7149

◆ invoke_item() [2/7]

bool npc::invoke_item ( item used)
overridevirtual

As above two, but with position equal to current position.

Reimplemented from Character.

Definition at line 3231 of file npc.cpp.

3232 {
3233  return Character::invoke_item( used );
3234 }
virtual bool invoke_item(item *, const tripoint &pt, int pre_obtain_moves=-1)
Asks how to use the item (if it has more than one use_method) and uses it.
Definition: character.cpp:7149

References Character::invoke_item().

◆ invoke_item() [3/7]

bool Character::invoke_item

Definition at line 1929 of file character.cpp.

7155 {
7156  return invoke_item( used, method, pos() );
7157 }

◆ invoke_item() [4/7]

bool Character::invoke_item

As above, but with a pre-selected method.

Debugmsg if this item doesn't have this method.

Definition at line 1925 of file character.cpp.

7161 {
7162  if( method.empty() ) {
7163  return invoke_item( used, pt, pre_obtain_moves );
7164  }
7165 
7166  if( used->is_broken() ) {
7167  add_msg_if_player( m_bad, _( "Your %s was broken and won't turn on." ), used->tname() );
7168  return false;
7169  }
7170  if( !used->ammo_sufficient( this, method ) ) {
7171  int ammo_req = used->ammo_required();
7172  std::string it_name = used->tname();
7173  if( used->has_flag( flag_USE_UPS ) ) {
7175  n_gettext( "Your %s needs %d charge from some UPS.",
7176  "Your %s needs %d charges from some UPS.",
7177  ammo_req ),
7178  it_name, ammo_req );
7179  } else if( used->has_flag( flag_USES_BIONIC_POWER ) ) {
7181  n_gettext( "Your %s needs %d kJ of bionic power.",
7182  "Your %s needs %d kJ of bionic power.",
7183  ammo_req ),
7184  it_name, ammo_req );
7185  } else {
7186  int ammo_rem = used->ammo_remaining();
7188  n_gettext( "Your %s has %d charge, but needs %d.",
7189  "Your %s has %d charges, but needs %d.",
7190  ammo_rem ),
7191  it_name, ammo_rem, ammo_req );
7192  }
7193  set_moves( pre_obtain_moves );
7194  return false;
7195  }
7196 
7197  item *actually_used = used->get_usable_item( method );
7198  if( actually_used == nullptr ) {
7199  debugmsg( "Tried to invoke a method %s on item %s, which doesn't have this method",
7200  method.c_str(), used->tname() );
7201  set_moves( pre_obtain_moves );
7202  return false;
7203  }
7204 
7205  std::optional<int> charges_used = actually_used->type->invoke( this, *actually_used,
7206  pt, method );
7207  if( !charges_used.has_value() ) {
7208  set_moves( pre_obtain_moves );
7209  return false;
7210  }
7211 
7212  if( charges_used.value() == 0 ) {
7213  // Not really used.
7214  // The item may also have been deleted
7215  return false;
7216  }
7217 
7218  if( actually_used->is_comestible() ) {
7219  const bool ret = consume_effects( *used );
7220  const int consumed = used->activation_consume( charges_used.value(), pt, this );
7221  if( consumed == 0 ) {
7222  // Nothing was consumed from within the item. "Eat" the item itself away.
7223  i_rem( actually_used );
7224  }
7225  return ret;
7226  }
7227 
7228  actually_used->activation_consume( charges_used.value(), pt, this );
7229 
7230  if( actually_used->has_flag( flag_SINGLE_USE ) || actually_used->is_bionic() ||
7231  actually_used->is_deployable() ) {
7232  i_rem( actually_used );
7233  return true;
7234  }
7235 
7236  return false;
7237 }
item i_rem(const item *it)
Remove a specific item from player possession.
bool consume_effects(item &food)
Handles the effects of consuming an item.
bool is_deployable() const
Definition: item.cpp:9948
const item * get_usable_item(const std::string &use_name) const
Checks this item and its contents (recursively) for types that have use_function with type use_name.
Definition: item.cpp:11508
bool is_bionic() const
Definition: item.cpp:9440
int activation_consume(int qty, const tripoint &pos, Character *carrier)
Consume ammo to activate item qty times (if available) and return the amount of ammo that was consume...
Definition: item.cpp:10990
bool is_comestible() const
Definition: item.cpp:9475
const flag_id flag_USE_UPS("USE_UPS")
const flag_id flag_USES_BIONIC_POWER("USES_BIONIC_POWER")
const flag_id flag_SINGLE_USE("SINGLE_USE")
#define n_gettext(STRING1, STRING2, COUNT)
Definition: translations.h:91

◆ invoke_item() [5/7]

bool npc::invoke_item ( item ,
const tripoint pt,
int  pre_obtain_moves 
)
overridevirtual

Asks how to use the item (if it has more than one use_method) and uses it.

Returns true if it destroys the item. Consumes charges from the item. Multi-use items are ONLY supported when all use_methods are iuse_actor!

Reimplemented from Character.

Definition at line 3214 of file npc.cpp.

3215 {
3216  const auto &use_methods = used->type->use_methods;
3217 
3218  if( use_methods.empty() ) {
3219  return false;
3220  } else if( use_methods.size() == 1 ) {
3221  return Character::invoke_item( used, use_methods.begin()->first, pt );
3222  }
3223  return false;
3224 }

References Character::invoke_item(), item::type, and itype::use_methods.

◆ invoke_item() [6/7]

bool Character::invoke_item

Asks how to use the item (if it has more than one use_method) and uses it.

Returns true if it destroys the item. Consumes charges from the item. Multi-use items are ONLY supported when all use_methods are iuse_actor!

Definition at line 1923 of file character.cpp.

7150 {
7151  return false;
7152 }

◆ invoke_item() [7/7]

bool npc::invoke_item ( item used,
const std::string &  method 
)
overridevirtual

Reimplemented from Character.

Definition at line 3226 of file npc.cpp.

3227 {
3228  return Character::invoke_item( used, method );
3229 }

References Character::invoke_item().

◆ is_active()

bool npc::is_active ( ) const

◆ is_ally()

bool npc::is_ally ( const Character p) const
overridevirtual

Implements Character.

Definition at line 2260 of file npc.cpp.

2261 {
2262  if( p.getID() == getID() ) {
2263  return true;
2264  }
2265  if( p.is_avatar() ) {
2266  if( my_fac && my_fac->id == faction_your_followers ) {
2267  return true;
2268  }
2269  if( faction_api_version < 2 ) {
2270  // legacy attitude support so let's be specific here
2271  if( attitude == NPCATT_FOLLOW || attitude == NPCATT_LEAD ||
2274  has_companion_mission() ) {
2275  return true;
2276  }
2277  }
2278  } else {
2279  const npc &guy = dynamic_cast<const npc &>( p );
2280  if( my_fac && guy.get_faction() && my_fac->id == guy.get_faction()->id ) {
2281  return true;
2282  }
2283  if( faction_api_version < 2 ) {
2284  Character &player_character = get_player_character();
2285  if( is_ally( player_character ) && guy.is_ally( player_character ) ) {
2286  return true;
2287  }
2288  if( get_attitude_group( get_attitude() ) ==
2289  guy.get_attitude_group( guy.get_attitude() ) ) {
2290  return true;
2291  }
2292  }
2293  }
2294  return false;
2295 }
static const faction_id faction_your_followers("your_followers")
@ NPCATT_WAIT
Definition: npc.h:113

References attitude, Character::faction_api_version, faction_your_followers, get_attitude(), get_attitude_group(), get_faction(), get_player_character(), Character::getID(), has_companion_mission(), faction_template::id, is_ally(), Creature::is_avatar(), Character::my_fac, NPC_MISSION_ACTIVITY, NPC_MISSION_GUARD_ALLY, NPC_MISSION_TRAVELLING, NPCATT_FOLLOW, NPCATT_LEAD, and NPCATT_WAIT.

Referenced by handle_sound(), indoor_voice(), avatar::is_ally(), is_ally(), is_friendly(), is_obeying(), is_player_ally(), move(), iuse::play_game(), talker_character_const::spell_training_text(), and talker_character_const::style_training_text().

◆ is_avatar()

bool npc::is_avatar ( ) const
inlineoverridevirtual

Reimplemented from Creature.

Definition at line 802 of file npc.h.

802  {
803  return false;
804  }

◆ is_dead()

bool npc::is_dead ( ) const

Definition at line 2746 of file npc.cpp.

2747 {
2748  return dead || is_dead_state();
2749 }
bool is_dead_state() const override
Returns true if the player should be dead.
Definition: character.cpp:1885

References dead, and Character::is_dead_state().

Referenced by jmapgen_remove_npcs::apply(), die(), and on_attacked().

◆ is_electrical()

bool npc::is_electrical ( ) const
inlineoverridevirtual

Reimplemented from Character.

Definition at line 917 of file npc.h.

917  {
918  // only beep on Rubik for now
919  return has_trait( trait_id( "EXODII_BODY_1" ) );
920  }

References Character::has_trait(), and trait_id.

◆ is_enemy()

bool npc::is_enemy ( ) const

◆ is_following()

bool npc::is_following ( ) const

◆ is_friendly()

bool npc::is_friendly ( const Character p) const

◆ is_guarding()

bool npc::is_guarding ( ) const

◆ is_hallucination()

bool npc::is_hallucination ( ) const
inlineoverridevirtual

◆ is_leader()

bool npc::is_leader ( ) const

Definition at line 2332 of file npc.cpp.

2333 {
2334  return attitude == NPCATT_LEAD;
2335 }

References attitude, and NPCATT_LEAD.

Referenced by extended_description(), get_current_status(), and talker_npc::get_topics().

◆ is_minion()

bool npc::is_minion ( ) const

Trusts you a lot.

Definition at line 2307 of file npc.cpp.

2308 {
2309  return is_player_ally() && op_of_u.trust >= 5;
2310 }

References is_player_ally(), op_of_u, and npc_opinion::trust.

Referenced by will_accept_from_player().

◆ is_npc()

bool npc::is_npc ( ) const
inlineoverridevirtual

Reimplemented from Character.

Definition at line 805 of file npc.h.

805  {
806  return true;
807  }

Referenced by game::npc_menu().

◆ is_obeying()

bool npc::is_obeying ( const Character p) const
overridevirtual

Implements Character.

Definition at line 2322 of file npc.cpp.

2323 {
2324  return is_ally( p ) && ( ( p.is_avatar() && is_walking_with() ) || is_stationary( true ) );
2325 }
bool is_stationary(bool include_guards=true) const
Definition: npc.cpp:2357

References is_ally(), Creature::is_avatar(), is_stationary(), and is_walking_with().

Referenced by avatar::is_obeying().

◆ is_patrolling()

bool npc::is_patrolling ( ) const

Definition at line 2371 of file npc.cpp.

2372 {
2374 }

References NPC_MISSION_GUARD_PATROL.

Referenced by get_current_status(), is_guarding(), and reach_omt_destination().

◆ is_player_ally()

bool npc::is_player_ally ( ) const

Definition at line 2297 of file npc.cpp.

2298 {
2299  return is_ally( get_player_character() );
2300 }

References get_player_character(), and is_ally().

Referenced by act_on_danger_assessment(), address_needs(), alt_attack(), assess_danger(), talk_function::assign_guard(), Character::attitude_to(), attitude_to(), basic_symbol_color(), Character::calc_spell_training_cost(), npc_attack_throw::can_use(), npc_attack_activate_item::can_use(), check_or_use_weapon_cbm(), complain(), confidence_mult(), consume_food(), consume_food_from_camp(), avatar::control_npc(), vehicle_part::crew(), do_player_activity(), evaluate_best_attack(), evaluate_best_weapon(), evaluate_character(), extended_description(), find_corpse_to_pulp(), find_item(), form_opinion(), friendly_teacher(), get_monster_faction(), talker_npc::get_topics(), go_to_omt_destination(), good_escape_direction(), handle_sound(), has_item_whitelist(), is_friendly(), is_minion(), talker_npc::is_player_ally(), is_shopkeeper(), long_term_goal_action(), make_angry(), max_credit_extended(), max_willing_to_owe(), move(), move_to(), mutiny(), game::npc_menu(), pick_up_item(), iuse::portable_game(), process_turn(), reach_omt_destination(), recharge_cbm(), regen_ai_cache(), vehicle_part::set_crew(), shop_restock(), smash_ability(), talk_function::start_training_seminar(), talk_function::stop_following(), talk_function::stop_guard(), trade_ui::trade_ui(), game::validate_npc_followers(), wield_better_weapon(), and will_exchange_items_freely().

◆ is_safe()

bool npc::is_safe ( ) const

Definition at line 1210 of file npcmove.cpp.

1211 {
1212  return ai_cache.total_danger <= 0;
1213 }

References ai_cache, and npc_short_term_cache::total_danger.

Referenced by talker_npc::is_safe().

◆ is_shopkeeper()

bool npc::is_shopkeeper ( ) const

Definition at line 2027 of file npc.cpp.

2028 {
2029  return !is_player_ally() && !myclass->get_shopkeeper_items().empty();
2030 }
const std::vector< shopkeeper_item_group > & get_shopkeeper_items() const
Definition: npc_class.cpp:417

References npc_class::get_shopkeeper_items(), is_player_ally(), and myclass.

Referenced by trade_ui::_confirm_trade(), shop_restock(), npc_trading::trade(), trade_ui::trade_ui(), value(), and wants_to_buy().

◆ is_stationary()

bool npc::is_stationary ( bool  include_guards = true) const

Definition at line 2357 of file npc.cpp.

2358 {
2359  if( include_guards && is_guarding() ) {
2360  return true;
2361  }
2364 }
static const efftype_id effect_infection("infection")

References effect_infection, Creature::has_effect(), is_guarding(), NPC_MISSION_SHELTER, and NPC_MISSION_SHOPKEEP.

Referenced by is_obeying(), move(), regen_ai_cache(), and set_omt_destination().

◆ is_travelling()

bool npc::is_travelling ( ) const

Definition at line 2381 of file npc.cpp.

2382 {
2383  return mission == NPC_MISSION_TRAVELLING;
2384 }

References NPC_MISSION_TRAVELLING.

Referenced by reach_omt_destination().

◆ is_walking_with()

bool npc::is_walking_with ( ) const

◆ item_name_whitelisted()

bool npc::item_name_whitelisted ( const std::string &  to_match)

Definition at line 7224 of file npctalk.cpp.

7225 {
7226  if( !has_item_whitelist() ) {
7227  return true;
7228  }
7229 
7231  const rule_state rule = wlist.check_item( to_match );
7232  if( rule == rule_state::WHITELISTED ) {
7233  return true;
7234  }
7235 
7236  if( rule == rule_state::BLACKLISTED ) {
7237  return false;
7238  }
7239 
7240  wlist.create_rule( to_match );
7241  return wlist.check_item( to_match ) == rule_state::WHITELISTED;
7242 }
rule_state check_item(const std::string &sItemName) const
void create_rule(const std::string &to_match)
rule_state
Definition: enums.h:109

References BLACKLISTED, auto_pickup::base_settings::check_item(), auto_pickup::npc_settings::create_rule(), has_item_whitelist(), npc_follower_rules::pickup_whitelist, rules, and WHITELISTED.

Referenced by find_item(), and item_whitelisted().

◆ item_whitelisted()

bool npc::item_whitelisted ( const item it)

Definition at line 7244 of file npctalk.cpp.

7245 {
7246  if( !has_item_whitelist() ) {
7247  return true;
7248  }
7249 
7250  const std::string to_match = it.tname( 1, false );
7251  return item_name_whitelisted( to_match );
7252 }

References has_item_whitelist(), item_name_whitelisted(), and item::tname().

Referenced by wants_take_that().

◆ learn_ma_styles_from_traits()

void npc::learn_ma_styles_from_traits ( )

Definition at line 723 of file npc.cpp.

724 {
725  for( const trait_id &iter : get_mutations() ) {
726  if( !iter->initial_ma_styles.empty() ) {
727  std::vector<matype_id> shuffled_trait_styles = iter->initial_ma_styles;
728  std::shuffle( shuffled_trait_styles.begin(), shuffled_trait_styles.end(), rng_get_engine() );
729 
730  for( const matype_id &style : shuffled_trait_styles ) {
731  if( !martial_arts_data->has_martialart( style ) ) {
732  martial_arts_data->learn_style( style, false );
733  break;
734  }
735  }
736  }
737  }
738 }
pimpl< character_martial_arts > martial_arts_data
Definition: character.h:2724
cata_default_random_engine & rng_get_engine()
Definition: rng.cpp:199

References Character::get_mutations(), Character::martial_arts_data, and rng_get_engine().

Referenced by randomize().

◆ load()

void npc::load ( const JsonObject data)
protected

Definition at line 2042 of file savegame_json.cpp.

2043 {
2044  Character::load( data );
2045 
2046  // TEMPORARY Remove if branch after 0.G (keep else branch)
2047  if( !data.has_member( "location" ) ) {
2048  point submap_coords;
2049  data.read( "submap_coords", submap_coords );
2050  const tripoint pos = read_legacy_creature_pos( data );
2051  set_location( tripoint_abs_ms( project_to<coords::ms>( point_abs_sm( submap_coords ) ),
2052  0 ) + tripoint( pos.x % SEEX, pos.y % SEEY, pos.z ) );
2053  std::optional<tripoint> opt;
2054  if( data.read( "last_player_seen_pos", opt ) && opt ) {
2055  last_player_seen_pos = get_location() + *opt - pos;
2056  }
2057  if( data.read( "pulp_location", opt ) && opt ) {
2058  pulp_location = get_location() + *opt - pos;
2059  }
2060  tripoint tmp;
2061  if( data.read( "guardx", tmp.x ) && data.read( "guardy", tmp.y ) && data.read( "guardz", tmp.z ) &&
2062  tmp != tripoint_min ) {
2063  guard_pos = tripoint_abs_ms( tmp );
2064  }
2065  if( data.read( "chair_pos", tmp ) && tmp != tripoint_min ) {
2066  chair_pos = tripoint_abs_ms( tmp );
2067  }
2068  if( data.read( "wander_pos", tmp ) && tmp != tripoint_min ) {
2069  wander_pos = tripoint_abs_ms( tmp );
2070  }
2071  } else {
2072  data.read( "last_player_seen_pos", last_player_seen_pos );
2073  data.read( "guard_pos", guard_pos );
2074  data.read( "pulp_location", pulp_location );
2075  data.read( "chair_pos", chair_pos );
2076  data.read( "wander_pos", wander_pos );
2077  }
2078 
2079  int misstmp = 0;
2080  int classtmp = 0;
2081  int atttmp = 0;
2082  std::string facID;
2083  std::string comp_miss_role;
2084  tripoint_abs_omt comp_miss_pt;
2085  std::string classid;
2086  std::string companion_mission_role;
2087  time_point companion_mission_t = calendar::turn_zero;
2088  time_point companion_mission_t_r = calendar::turn_zero;
2089  std::string act_id;
2090 
2091  // Remove after 0.F
2092  // Exists to prevent failed to visit member errors
2093  if( data.has_member( "reactor_plut" ) ) {
2094  data.get_int( "reactor_plut" );
2095  }
2096  if( data.has_member( "tank_plut" ) ) {
2097  data.get_int( "tank_plut" );
2098  }
2099 
2100  data.read( "marked_for_death", marked_for_death );
2101  data.read( "dead", dead );
2102  data.read( "patience", patience );
2103  if( data.has_number( "myclass" ) ) {
2104  data.read( "myclass", classtmp );
2105  myclass = npc_class::from_legacy_int( classtmp );
2106  } else if( data.has_string( "myclass" ) ) {
2107  data.read( "myclass", classid );
2108  myclass = npc_class_id( classid );
2109  }
2110  if( data.has_string( "idz" ) ) {
2111  data.read( "idz", idz );
2112  } else {
2114  }
2115  data.read( "known_to_u", known_to_u );
2116  data.read( "personality", personality );
2117 
2118  data.read( "goalx", goal.x() );
2119  data.read( "goaly", goal.y() );
2120  data.read( "goalz", goal.z() );
2121 
2122  if( data.read( "current_activity_id", act_id ) ) {
2123  current_activity_id = activity_id( act_id );
2124  } else if( activity ) {
2126  }
2127 
2128  data.read( "assigned_camp", assigned_camp );
2129  data.read( "job", job );
2130  if( data.read( "mission", misstmp ) ) {
2131  mission = static_cast<npc_mission>( misstmp );
2132  static const std::set<npc_mission> legacy_missions = {{
2135  }
2136  };
2137  if( legacy_missions.count( mission ) > 0 ) {
2139  }
2140  }
2141  if( data.read( "previous_mission", misstmp ) ) {
2142  previous_mission = static_cast<npc_mission>( misstmp );
2143  static const std::set<npc_mission> legacy_missions = {{
2146  }
2147  };
2148  if( legacy_missions.count( mission ) > 0 ) {
2150  }
2151  }
2152 
2153  if( data.read( "my_fac", facID ) ) {
2154  fac_id = faction_id( facID );
2155  }
2156  int temp_fac_api_ver = 0;
2157  if( data.read( "faction_api_ver", temp_fac_api_ver ) ) {
2158  faction_api_version = temp_fac_api_ver;
2159  } else {
2160  faction_api_version = 0;
2161  }
2162 
2163  if( data.read( "attitude", atttmp ) ) {
2164  attitude = static_cast<npc_attitude>( atttmp );
2165  static const std::set<npc_attitude> legacy_attitudes = {{
2168  }
2169  };
2170  if( legacy_attitudes.count( attitude ) > 0 ) {
2172  }
2173  }
2174  if( data.read( "previous_attitude", atttmp ) ) {
2175  previous_attitude = static_cast<npc_attitude>( atttmp );
2176  static const std::set<npc_attitude> legacy_attitudes = {{
2179  }
2180  };
2181  if( legacy_attitudes.count( attitude ) > 0 ) {
2183  }
2184  }
2185 
2186  data.read( "comp_mission_id", comp_mission.miss_id );
2187 
2188  if( data.read( "comp_mission_pt", comp_miss_pt ) ) {
2189  comp_mission.position = comp_miss_pt;
2190  }
2191 
2192  if( data.read( "comp_mission_role", comp_miss_role ) ) {
2193  comp_mission.role_id = comp_miss_role;
2194  }
2195 
2196  if( data.read( "companion_mission_role_id", companion_mission_role ) ) {
2197  companion_mission_role_id = companion_mission_role;
2198  }
2199 
2200  std::vector<tripoint_abs_omt> companion_mission_pts;
2201  data.read( "companion_mission_points", companion_mission_pts );
2202  for( auto pt : companion_mission_pts ) {
2203  companion_mission_points.push_back( pt );
2204  }
2205 
2206  if( !data.read( "companion_mission_time", companion_mission_t ) ) {
2208  } else {
2209  companion_mission_time = companion_mission_t;
2210  }
2211 
2212  if( !data.read( "companion_mission_time_ret", companion_mission_t_r ) ) {
2214  } else {
2215  companion_mission_time_ret = companion_mission_t_r;
2216  }
2217 
2219  if( data.has_member( "companion_mission_inv" ) ) {
2220  companion_mission_inv.json_load_items( data.get_member( "companion_mission_inv" ) );
2221  }
2222 
2223  if( !data.read( "restock", restock ) ) {
2225  }
2226 
2227  data.read( "op_of_u", op_of_u );
2228  data.read( "chatbin", chatbin );
2229  if( !data.read( "rules", rules ) ) {
2230  data.read( "misc_rules", rules );
2231  data.read( "combat_rules", rules );
2232  }
2233  real_weapon = item();
2234  data.read( "real_weapon", real_weapon );
2235 
2236  complaints.clear();
2237  for( const JsonMember member : data.get_object( "complaints" ) ) {
2238  // TODO: time_point does not have a default constructor, need to read in the map manually
2240  member.read( p );
2241  complaints.emplace( member.name(), p );
2242  }
2243  data.read( "unique_id", unique_id );
2246 }
void load(const JsonObject &data)
Gather variables for saving.
bool has_number(std::string_view key) const
JsonObject get_object(std::string_view key) const
int get_int(std::string_view key) const
bool has_member(std::string_view key) const
bool read(std::string_view name, T &t, bool throw_on_error=true) const
JsonValue get_member(std::string_view key) const
bool has_string(std::string_view key) const
constexpr auto z() const
Definition: coordinates.h:167
void json_load_items(const JsonArray &ja)
static const npc_class_id & from_legacy_int(int i)
Definition: npc_class.cpp:376
void clear_personality_traits()
Definition: npc.cpp:697
void generate_personality_traits()
Definition: npc.cpp:706
A point in the game time.
Definition: calendar.h:460
@ member
coords::coord_point< tripoint, coords::origin::abs, coords::ms > tripoint_abs_ms
Definition: coordinates.h:712
coords::coord_point< point, coords::origin::abs, coords::sm > point_abs_sm
Definition: coordinates.h:698
string_id< npc_class > npc_class_id
Definition: item.cpp:236
npc_attitude
Definition: npc.h:106
@ NPCATT_LEGACY_3
Definition: npc.h:119
@ NPCATT_LEGACY_6
Definition: npc.h:114
@ NPCATT_LEGACY_4
Definition: npc.h:122
@ NPCATT_LEGACY_5
Definition: npc.h:123
@ NPCATT_LEGACY_1
Definition: npc.h:109
@ NPCATT_LEGACY_2
Definition: npc.h:111
npc_mission
Definition: npc.h:171
@ NPC_MISSION_LEGACY_2
Definition: npc.h:177
@ NPC_MISSION_LEGACY_3
Definition: npc.h:178
@ NPC_MISSION_LEGACY_1
Definition: npc.h:173
static tripoint read_legacy_creature_pos(const JsonObject &data)
tripoint_abs_omt position
Definition: npc.h:189
std::string role_id
Definition: npc.h:190

References activity_id, calendar::before_time_starts, item_pocket::data, faction_id, npc_class::from_legacy_int(), item, Character::load(), member, NPC_MISSION_LEGACY_1, NPC_MISSION_LEGACY_2, NPC_MISSION_LEGACY_3, NPC_MISSION_NULL, NPCATT_LEGACY_1, NPCATT_LEGACY_2, NPCATT_LEGACY_3, NPCATT_LEGACY_4, NPCATT_LEGACY_5, NPCATT_LEGACY_6, NPCATT_NULL, math_opers::pos(), read_legacy_creature_pos(), SEEX, SEEY, calendar::set_location(), tripoint, tripoint_min, calendar::turn_zero, tripoint::x, tripoint::y, and tripoint::z.

◆ load_npc_template()

void npc::load_npc_template ( const string_id< npc_template > &  ident)

Definition at line 501 of file npc.cpp.

502 {
503  auto found = npc_templates.find( ident );
504  if( found == npc_templates.end() ) {
505  debugmsg( "Tried to get invalid npc: %s", ident.c_str() );
506  return;
507  }
508  const npc_template &tem = found->second;
509  const npc &tguy = tem.guy;
510 
511  idz = ident;
512  myclass = npc_class_id( tguy.myclass );
513  randomize( myclass, ident );
516  }
517  name = SNIPPET.expand( male ? "<male_full_name>" : "<female_full_name>" );
518  if( !tem.name_unique.empty() ) {
519  name = tem.name_unique.translated();
520  }
521  if( !tem.name_suffix.empty() ) {
522  //~ %1$s: npc name, %2$s: name suffix
523  name = string_format( pgettext( "npc name", "%1$s, %2$s" ), name, tem.name_suffix );
524  }
525  fac_id = tguy.fac_id;
526  set_fac( fac_id );
527  attitude = tguy.attitude;
528  mission = tguy.mission;
542 
543  for( const mission_type_id &miss_id : tguy.miss_ids ) {
544  add_new_mission( mission::reserve_new( miss_id, getID() ) );
545  }
546  death_eocs = tguy.death_eocs;
547 }
static mission * reserve_new(const mission_type_id &type, const character_id &npc_id)
Create a new mission of the given type and assign it to the given npc.
Definition: mission.cpp:79
translation name_unique
Definition: npc.h:1498
translation name_suffix
Definition: npc.h:1499
gender gender_override
Definition: npc.h:1505
npc guy
Definition: npc.h:1496
void randomize(const npc_class_id &type=npc_class_id::NULL_ID(), const npc_template_id &tem_id=npc_template_id::NULL_ID())
Definition: npc.cpp:551
void add_new_mission(mission *miss)
See dialogue_chatbin::add_new_mission.
Definition: npc.cpp:3052
std::vector< mission_type_id > miss_ids
Definition: npc.h:1332
void set_fac(const faction_id &id)
Definition: npc.cpp:747
std::string expand(const std::string &str) const
Expand the string by recursively replacing tags in angle brackets (<>) with random snippets from the ...
const char * c_str() const
Interface to the plain C-string of the id.
Definition: string_id.h:252
bool empty() const
Whether the underlying string is empty, not matter what the context is or whether translation is need...
static std::map< string_id< npc_template >, npc_template > npc_templates
Definition: npc.cpp:291

References add_new_mission(), attitude, string_id< T >::c_str(), chatbin, Character::death_eocs, debugmsg, translation::empty(), snippet_library::expand(), Character::fac_id, dialogue_chatbin::first_topic, npc_template::gender_override, Character::getID(), npc_template::guy, idz, Character::male, npc_template::male, miss_ids, mission, myclass, Character::name, npc_template::name_suffix, npc_template::name_unique, npc_templates, pgettext, npc_template::random, randomize(), mission::reserve_new(), set_fac(), SNIPPET, string_format(), dialogue_chatbin::talk_friend, dialogue_chatbin::talk_friend_guard, dialogue_chatbin::talk_leader, dialogue_chatbin::talk_mug, dialogue_chatbin::talk_radio, dialogue_chatbin::talk_stole_item, dialogue_chatbin::talk_stranger_aggressive, dialogue_chatbin::talk_stranger_friendly, dialogue_chatbin::talk_stranger_neutral, dialogue_chatbin::talk_stranger_scared, dialogue_chatbin::talk_stranger_wary, dialogue_chatbin::talk_wake_up, and translation::translated().

◆ long_term_goal_action()

npc_action npc::long_term_goal_action ( )

Definition at line 2630 of file npcmove.cpp.

2631 {
2632  add_msg_debug( debugmode::DF_NPC, "long_term_goal_action()" );
2633 
2636  return npc_pause; // Shopkeepers just stay put.
2637  }
2638 
2639  if( !has_omt_destination() ) {
2641  }
2642 
2643  if( has_omt_destination() ) {
2644  if( mission != NPC_MISSION_TRAVELLING ) {
2647  }
2648  return npc_goto_destination;
2649  }
2650 
2651  return npc_undecided;
2652 }
void set_mission(npc_mission new_mission)
Definition: npc.cpp:3530

References add_msg_debug, attitude, debugmode::DF_NPC, has_omt_destination(), is_player_ally(), npc_goto_destination, NPC_MISSION_SHELTER, NPC_MISSION_SHOPKEEP, NPC_MISSION_TRAVELLING, npc_pause, npc_undecided, set_attitude(), set_mission(), and set_omt_destination().

Referenced by talk_function::leave(), and move().

◆ look_for_player()

void npc::look_for_player ( const Character sought)

Definition at line 4743 of file npcmove.cpp.

4744 {
4745  complain_about( "look_for_player", 5_minutes, chat_snippets().snip_wait.translated(), false );
4746  update_path( sought.pos() );
4747  move_to_next();
4748  // The part below is not implemented properly
4749  /*
4750  if( sees( sought ) ) {
4751  move_pause();
4752  return;
4753  }
4754 
4755  if (!path.empty()) {
4756  const tripoint &dest = path[path.size() - 1];
4757  if( !sees( dest ) ) {
4758  move_to_next();
4759  return;
4760  }
4761  path.clear();
4762  }
4763  std::vector<point> possibilities;
4764  for (int x = 1; x < MAPSIZE_X; x += 11) { // 1, 12, 23, 34
4765  for (int y = 1; y < MAPSIZE_Y; y += 11) {
4766  if( sees( x, y ) ) {
4767  possibilities.push_back(point(x, y));
4768  }
4769  }
4770  }
4771  if (possibilities.empty()) { // We see all the spots we'd like to check!
4772  say("<wait>");
4773  move_pause();
4774  } else {
4775  if (one_in(6)) {
4776  say("<wait>");
4777  }
4778  update_path( tripoint( random_entry( possibilities ), posz() ) );
4779  move_to_next();
4780  }
4781  */
4782 }

References chat_snippets(), complain_about(), move_to_next(), Creature::pos(), and update_path().

Referenced by execute_action(), and npc_attack_melee::use().

◆ make_angry()

void npc::make_angry ( )

Definition at line 1626 of file npc.cpp.

1627 {
1628  if( is_enemy() ) {
1629  return; // We're already angry!
1630  }
1631 
1632  // player allies that become angry should stop being player allies
1633  if( is_player_ally() ) {
1634  mutiny();
1635  }
1636 
1637  // Make associated faction, if any, angry at the player too.
1638  if( my_fac && my_fac->id != faction_no_faction && my_fac->id != faction_amf ) {
1639  my_fac->likes_u = std::min( -15, my_fac->likes_u - 5 );
1640  my_fac->respects_u = std::min( -15, my_fac->respects_u - 5 );
1641  my_fac->trusts_u = std::min( -15, my_fac->trusts_u - 5 );
1642  }
1644  set_attitude( NPCATT_FLEE_TEMP ); // We don't want to take u on!
1645  } else {
1646  set_attitude( NPCATT_KILL ); // Yeah, we think we could take you!
1647  }
1648 }
static const faction_id faction_amf("amf")

References npc_personality::aggression, npc_personality::bravery, faction_amf, faction_no_faction, npc_opinion::fear, faction_template::id, is_enemy(), is_player_ally(), faction_template::likes_u, min(), mutiny(), Character::my_fac, NPCATT_FLEE_TEMP, NPCATT_KILL, op_of_u, personality, faction_template::respects_u, set_attitude(), and faction_template::trusts_u.

Referenced by Character::disassemble(), talker_npc::get_topics(), vehicle::handle_potential_theft(), talker_npc::make_angry(), avatar_action::move(), mug_player(), and on_attacked().

◆ max_credit_extended()

int npc::max_credit_extended ( ) const

Definition at line 1883 of file npc.cpp.

1884 {
1885  if( is_player_ally() ) {
1886  return INT_MAX;
1887  }
1888 
1889  const int credit_trust = 50;
1890  const int credit_value = 50;
1891  const int credit_fear = 50;
1892  const int credit_altruism = 100;
1893  const int credit_anger = -200;
1894 
1895  return std::max( 0,
1896  op_of_u.trust * credit_trust +
1897  op_of_u.value * credit_value +
1898  op_of_u.fear * credit_fear +
1899  personality.altruism * credit_altruism +
1900  op_of_u.anger * credit_anger
1901  );
1902 }
int anger
Definition: npc.h:236

References npc_personality::altruism, npc_opinion::anger, npc_opinion::fear, is_player_ally(), max(), op_of_u, personality, npc_opinion::trust, and npc_opinion::value.

Referenced by trade_ui::_confirm_trade(), and npc_trading::npc_will_accept_trade().

◆ max_willing_to_owe()

int npc::max_willing_to_owe ( ) const

Definition at line 1906 of file npc.cpp.

1907 {
1908  if( is_player_ally() ) {
1909  return INT_MAX;
1910  }
1911 
1912  const int credit_trust = 10000;
1913  const int credit_value = 10000;
1914  const int credit_fear = 10000;
1915  const int credit_altruism = 10000;
1916  const int credit_anger = -10000;
1917  const int credit_default = 10000;
1918 
1919  // NPCs will usually be happy to owe at least credit_default, but may be willing to owe
1920  // more if they trust, value, are fearful, or altruistic.
1921  // Angry NPCs could conceiveably refuse to owe you money, out of spite.
1922  return std::max( 0,
1923  credit_default +
1924  std::max( 0, op_of_u.trust ) * credit_trust +
1925  std::max( 0, op_of_u.value ) * credit_value +
1926  std::max( 0, op_of_u.fear ) * credit_fear +
1927  std::max( 0, static_cast<int>( personality.altruism ) ) * credit_altruism +
1928  op_of_u.anger * credit_anger
1929  );
1930 
1931 }

References npc_personality::altruism, npc_opinion::anger, npc_opinion::fear, is_player_ally(), max(), op_of_u, personality, npc_opinion::trust, and npc_opinion::value.

Referenced by trade_ui::_confirm_trade(), and npc_trading::calc_npc_owes_you().

◆ method_of_attack()

npc_action npc::method_of_attack ( )

Definition at line 1962 of file npcmove.cpp.

1963 {
1964  Creature *critter = current_target();
1965  if( critter == nullptr ) {
1966  // This function shouldn't be called...
1967  debugmsg( "Ran npc::method_of_attack without a target!" );
1968  return npc_pause;
1969  }
1970 
1971  // if there's enough of a threat to be here, power up the combat CBMs and any combat items.
1973 
1974  evaluate_best_attack( critter );
1975 
1976  std::optional<int> potential = ai_cache.current_attack_evaluation.value();
1977  if( potential && *potential > 0 ) {
1978  return npc_do_attack;
1979  } else {
1980  add_msg_debug( debugmode::debug_filter::DF_NPC, "%s can't figure out what to do", disp_name() );
1981  return npc_undecided;
1982  }
1983 }
std::optional< int > value() const
Definition: npc_attack.h:27
void prepare_for_combat()
Definition: npcmove.cpp:2369
void evaluate_best_attack(const Creature *target)
Definition: npcmove.cpp:1985

References add_msg_debug, ai_cache, npc_short_term_cache::current_attack_evaluation, current_target(), debugmsg, debugmode::DF_NPC, Character::disp_name(), evaluate_best_attack(), npc_do_attack, npc_pause, npc_undecided, prepare_for_combat(), and npc_attack_rating::value().

Referenced by move().

◆ method_of_fleeing()

npc_action npc::method_of_fleeing ( )

Definition at line 1954 of file npcmove.cpp.

1955 {
1956  if( in_vehicle ) {
1957  return npc_undecided;
1958  }
1959  return npc_flee;
1960 }

References Character::in_vehicle, npc_flee, and npc_undecided.

Referenced by move().

◆ minimum_item_value()

int npc::minimum_item_value ( ) const

Definition at line 2032 of file npc.cpp.

2033 {
2034  // TODO: Base on inventory
2035  int ret = 20;
2037  return ret;
2038 }

References npc_personality::collector, personality, and cata::hash64_detail::ret.

Referenced by find_item(), mug_player(), and wants_take_that().

◆ move()

void npc::move ( )

Definition at line 1301 of file npcmove.cpp.

1302 {
1303  // don't just return from this function without doing something
1304  // that will eventually subtract moves, or change the NPC to a different type of action.
1305  // because this will result in an infinite loop
1306  if( attitude == NPCATT_FLEE ) {
1307  set_attitude( NPCATT_FLEE_TEMP ); // Only run for so many hours
1310  }
1311  regen_ai_cache();
1312  // NPCs under operation should just stay still
1313  if( activity.id() == ACT_OPERATION || activity.id() == ACT_SPELLCASTING ) {
1315  return;
1316  }
1319 
1321  static const std::string no_target_str = "none";
1322  const Creature *target = current_target();
1323  const std::string &target_name = target != nullptr ? target->disp_name() : no_target_str;
1324  if( !confident_range_cache ) {
1326  }
1327  add_msg_debug( debugmode::DF_NPC, "NPC %s: target = %s, danger = %.1f, range = %d",
1328  get_name(), target_name, ai_cache.danger, *confident_range_cache );
1329 
1330  Character &player_character = get_player_character();
1331  //faction opinion determines if it should consider you hostile
1332  if( !is_enemy() && guaranteed_hostile() && sees( player_character ) ) {
1333  if( is_player_ally() ) {
1334  mutiny();
1335  }
1336  add_msg_debug( debugmode::DF_NPC, "NPC %s turning hostile because is guaranteed_hostile()",
1337  get_name() );
1339  set_attitude( NPCATT_FLEE_TEMP ); // We don't want to take u on!
1340  } else {
1341  set_attitude( NPCATT_KILL ); // Yeah, we think we could take you!
1342  }
1343  }
1344 
1345  /* This bypasses the logic to determine the npc action, but this all needs to be rewritten
1346  * anyway.
1347  * NPC won't avoid dangerous terrain while accompanying the player inside a vehicle to keep
1348  * them from inadvertently getting themselves run over and/or cause vehicle related errors.
1349  * NPCs flee from uncontained fires within 3 tiles
1350  */
1352  if( sees_dangerous_field( pos() ) ) {
1353  path.clear();
1354  }
1355  const tripoint escape_dir = good_escape_direction( sees_dangerous_field( pos() ) );
1356  if( escape_dir != pos() ) {
1357  move_to( escape_dir );
1358  return;
1359  }
1360  }
1361 
1362  // TODO: Place player-aiding actions here, with a weight
1363 
1364  /* NPCs are fairly suicidal so at this point we will do a quick check to see if
1365  * something nasty is going to happen.
1366  */
1367 
1369  // TODO: Think about how this actually needs to work, for now assume flee from player
1370  ai_cache.target = g->shared_from( player_character );
1371  }
1372 
1373  map &here = get_map();
1374  if( !ai_cache.dangerous_explosives.empty() ) {
1376  } else if( ( target == &player_character && attitude == NPCATT_FLEE_TEMP ) ||
1379  } else if( has_effect( effect_asthma ) && ( has_charges( itype_inhaler, 1 ) ||
1381  has_charges( itype_smoxygen_tank, 1 ) ) ) {
1382  action = npc_heal;
1383  } else if( target != nullptr && ai_cache.danger > 0 ) {
1385  } else if( !ai_cache.sound_alerts.empty() && !is_walking_with() ) {
1386  tripoint cur_s_abs_pos = ai_cache.s_abs_pos;
1387  if( !ai_cache.guard_pos ) {
1389  }
1390  if( ai_cache.sound_alerts.size() > 1 ) {
1391  std::sort( ai_cache.sound_alerts.begin(), ai_cache.sound_alerts.end(),
1393  if( ai_cache.sound_alerts.size() > 10 ) {
1394  ai_cache.sound_alerts.resize( 10 );
1395  }
1396  }
1397  if( has_trait( trait_IGNORE_SOUND ) ) { //Do not investigate sounds - clear sound alerts as below
1398  ai_cache.sound_alerts.clear();
1400  } else {
1402  }
1403  if( ai_cache.sound_alerts.front().abs_pos != cur_s_abs_pos ) {
1404  ai_cache.stuck = 0;
1405  ai_cache.s_abs_pos = ai_cache.sound_alerts.front().abs_pos;
1406  } else if( ai_cache.stuck > 10 ) {
1407  ai_cache.stuck = 0;
1408  if( ai_cache.sound_alerts.size() == 1 ) {
1409  ai_cache.sound_alerts.clear();
1411  } else {
1412  ai_cache.s_abs_pos = ai_cache.sound_alerts.at( 1 ).abs_pos;
1413  }
1414  }
1415  if( action == npc_investigate_sound ) {
1416  add_msg_debug( debugmode::DF_NPC, "NPC %s: investigating sound at x(%d) y(%d)", get_name(),
1418  }
1419  } else {
1420  // No present danger
1422 
1423  action = address_needs();
1424  print_action( "address_needs %s", action );
1425 
1426  if( action == npc_undecided ) {
1427  action = address_player();
1428  print_action( "address_player %s", action );
1429  }
1430  if( action == npc_undecided && ai_cache.sound_alerts.empty() && ai_cache.guard_pos ) {
1431  tripoint_abs_ms return_guard_pos = *ai_cache.guard_pos;
1432  add_msg_debug( debugmode::DF_NPC, "NPC %s: returning to guard spot at x(%d) y(%d)", get_name(),
1433  return_guard_pos.x(), return_guard_pos.y() );
1435  }
1436  }
1437 
1440  }
1441 
1442  // check if in vehicle before doing any other follow activities
1443  if( action == npc_undecided && is_walking_with() && player_character.in_vehicle &&
1444  !in_vehicle ) {
1446  path.clear();
1447  }
1448 
1450  rl_dist( pos(), player_character.pos() ) > follow_distance() && !( player_character.in_vehicle &&
1451  in_vehicle ) ) {
1453  }
1454 
1455  if( action == npc_undecided && attitude == NPCATT_ACTIVITY ) {
1456  if( has_stashed_activity() ) {
1459  } else {
1460  // wait a turn, because next turn, the object of our activity
1461  // may have been loaded in.
1462  set_moves( 0 );
1463  }
1464  return;
1465  }
1466  std::vector<tripoint_bub_ms> activity_route = get_auto_move_route();
1467  if( !activity_route.empty() && !has_destination_activity() ) {
1468  tripoint_bub_ms final_destination;
1469  if( destination_point ) {
1470  final_destination = here.bub_from_abs( *destination_point );
1471  } else {
1472  final_destination = activity_route.back();
1473  }
1474  // TODO: fix point types
1475  update_path( final_destination.raw() );
1476  if( !path.empty() ) {
1477  move_to_next();
1478  return;
1479  }
1480  }
1481  if( has_destination_activity() ) {
1484  } else if( has_player_activity() ) {
1486  }
1487  }
1488  if( action == npc_undecided ) {
1489  // an interrupted activity can cause this situation. stops allied NPCs zooming off
1490  // like random NPCs
1491  if( attitude == NPCATT_ACTIVITY && !activity ) {
1493  if( is_ally( player_character ) && !assigned_camp ) {
1496  }
1497  }
1498  if( assigned_camp && attitude != NPCATT_ACTIVITY ) {
1499  if( has_job() && calendar::once_every( 10_minutes ) && find_job_to_perform() ) {
1501  } else {
1504  }
1505  }
1506  if( is_stationary( true ) && !assigned_camp ) {
1507  // if we're in a vehicle, stay in the vehicle
1508  if( in_vehicle ) {
1509  action = npc_pause;
1511  } else {
1513  }
1514  } else if( has_new_items && scan_new_items() ) {
1515  return;
1516  } else if( !fetching_item ) {
1517  find_item();
1518  print_action( "find_item %s", action );
1519  } else if( assigned_camp ) {
1520  // this should be covered above, but justincase to stop them zooming away.
1521  action = npc_pause;
1522  }
1523 
1524  // check if in vehicle before rushing off to fetch things
1525  if( is_walking_with() && player_character.in_vehicle ) {
1527  path.clear();
1528  } else if( fetching_item ) {
1529  // Set to true if find_item() found something
1530  action = npc_pickup;
1531  } else if( is_following() ) {
1532  // No items, so follow the player?
1534  }
1535  // Friendly NPCs who are followers/ doing tasks for the player should never get here.
1536  // This will revert them to a dynamic NPC state.
1537  if( action == npc_undecided ) {
1538  // Do our long-term action
1540  print_action( "long_term_goal_action %s", action );
1541  }
1542  }
1543 
1544  /* Sometimes we'll be following the player at this point, but close enough that
1545  * "following" means standing still. If that's the case, if there are any
1546  * monsters around, we should attack them after all!
1547  *
1548  * If we are following a embarked player and we are in a vehicle then shoot anyway
1549  * as we are most likely riding shotgun
1550  */
1551  if( ai_cache.danger > 0 && target != nullptr &&
1552  (
1554  ( action == npc_follow_player &&
1555  ( rl_dist( pos(), player_character.pos() ) <= follow_distance() ||
1556  posz() != player_character.posz() ) )
1557  ) ) {
1559  }
1560 
1561  add_msg_debug( debugmode::DF_NPC, "%s chose action %s.", get_name(), npc_action_name( action ) );
1563 }
std::vector< tripoint_bub_ms > & get_auto_move_route()
bool check_outbounds_activity(const player_activity &act, bool check_only=false)
Definition: character.cpp:1553
void assign_stashed_activity()
Definition: character.cpp:1546
std::optional< tripoint > destination_point
Definition: character.h:2711
player_activity get_stashed_activity() const
Definition: character.cpp:1530
bool has_destination_activity() const
void start_destination_activity()
bool has_charges(const itype_id &it, int quantity, const std::function< bool(const item &)> &filter=return_true< item >) const override
Definition: character.cpp:9586
bool has_stashed_activity() const
Definition: character.cpp:1541
virtual std::string disp_name(bool possessive=false, bool capitalize_first=false) const =0
tripoint_bub_ms bub_from_abs(const tripoint &p) const
Definition: map.cpp:9647
void regen_ai_cache()
Definition: npcmove.cpp:1215
bool find_job_to_perform()
Definition: npcmove.cpp:3262
float vehicle_danger(int radius) const
Definition: npc.cpp:1573
void cleanup_on_no_danger()
Definition: npcmove.cpp:2375
void act_on_danger_assessment()
Definition: npcmove.cpp:1101
void find_item()
Definition: npcmove.cpp:3492
npc_action address_player()
Definition: npcmove.cpp:2570
npc_action method_of_fleeing()
Definition: npcmove.cpp:1954
npc_action long_term_goal_action()
Definition: npcmove.cpp:2630
bool has_player_activity() const
is performing a player_activity
Definition: npc.cpp:2376
bool scan_new_items()
Definition: npcmove.cpp:4142
npc_action method_of_attack()
Definition: npcmove.cpp:1962
bool once_every(const time_duration &event_frequency)
Predicate to handle rate-limiting.
Definition: calendar.cpp:753
static const itype_id itype_oxygen_tank("oxygen_tank")
static const itype_id itype_inhaler("inhaler")
static const itype_id itype_smoxygen_tank("smoxygen_tank")
static const activity_id ACT_OPERATION("ACT_OPERATION")
static const activity_id ACT_SPELLCASTING("ACT_SPELLCASTING")
static const trait_id trait_IGNORE_SOUND("IGNORE_SOUND")
static void print_action(const char *prepend, npc_action action)
Definition: npcmove.cpp:5089
static bool compare_sound_alert(const dangerous_sound &sound_a, const dangerous_sound &sound_b)
Definition: npcmove.cpp:234
static const efftype_id effect_npc_flee_player("npc_flee_player")

References act_on_danger_assessment(), ACT_OPERATION, ACT_SPELLCASTING, action, Character::activity, add_msg_debug, address_needs(), address_player(), npc_personality::aggression, ai_cache, Character::assign_stashed_activity(), assigned_camp, attitude, anonymous_namespace{npcmove.cpp}::avoidance_vehicles_radius, npc_personality::bravery, map::bub_from_abs(), Character::check_outbounds_activity(), cleanup_on_no_danger(), compare_sound_alert(), confident_range_cache, current_target(), npc_short_term_cache::danger, npc_short_term_cache::dangerous_explosives, Character::destination_point, debugmode::DF_NPC, Creature::disp_name(), effect_asthma, effect_npc_fire_bad, effect_npc_flee_player, effect_npc_run_away, execute_action(), npc_opinion::fear, fetching_item, find_item(), find_job_to_perform(), follow_close, follow_distance(), g, Character::get_auto_move_route(), Creature::get_location(), get_map(), Character::get_name(), get_player_character(), Character::get_stashed_activity(), Character::get_wielded_item(), Creature::global_omt_location(), goal, good_escape_direction(), goto_to_this_pos, guaranteed_hostile(), npc_short_term_cache::guard_pos, Character::has_charges(), Character::has_destination_activity(), Creature::has_effect(), npc_follower_rules::has_flag(), has_job(), has_new_items, has_player_activity(), Character::has_stashed_activity(), Character::has_trait(), player_activity::id(), Character::in_vehicle, invalidate_range_cache(), is_ally(), is_enemy(), is_following(), is_player_ally(), is_stationary(), is_walking_with(), itype_inhaler, itype_oxygen_tank, itype_smoxygen_tank, long_term_goal_action(), method_of_attack(), method_of_fleeing(), move_to(), move_to_next(), mutiny(), npc_action_name(), npc_escape_explosion, npc_follow_embarked, npc_follow_player, npc_goto_destination, npc_goto_to_this_pos, npc_heal, npc_investigate_sound, NPC_MISSION_NULL, npc_pause, npc_pickup, npc_player_activity, npc_return_to_guard_pos, npc_undecided, npc_worker_downtime, NPCATT_ACTIVITY, NPCATT_FLEE, NPCATT_FLEE_TEMP, NPCATT_FOLLOW, NPCATT_KILL, NPCATT_NULL, calendar::once_every(), op_of_u, path, personality, Creature::pos(), Creature::posz(), print_action(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), regen_ai_cache(), revert_after_activity(), rl_dist(), rules, npc_short_term_cache::s_abs_pos, scan_new_items(), Character::sees(), sees_dangerous_field(), set_attitude(), Creature::set_moves(), npc_short_term_cache::sound_alerts, Character::start_destination_activity(), npc_short_term_cache::stuck, npc_short_term_cache::target, trait_IGNORE_SOUND, update_path(), vehicle_danger(), Character::weapon, coords::coord_point_mut< Point, Subpoint, InBounds >::x(), tripoint::x, coords::coord_point_mut< Point, Subpoint, InBounds >::y(), and tripoint::y.

◆ move_away_from() [1/2]

void npc::move_away_from ( const std::vector< sphere > &  spheres,
bool  no_bashing = false 
)

Definition at line 3425 of file npcmove.cpp.

3426 {
3427  if( spheres.empty() ) {
3428  return;
3429  }
3430 
3431  tripoint minp( pos() );
3432  tripoint maxp( pos() );
3433 
3434  for( const sphere &elem : spheres ) {
3435  minp.x = std::min( minp.x, elem.center.x - elem.radius );
3436  minp.y = std::min( minp.y, elem.center.y - elem.radius );
3437  maxp.x = std::max( maxp.x, elem.center.x + elem.radius );
3438  maxp.y = std::max( maxp.y, elem.center.y + elem.radius );
3439  }
3440 
3441  const tripoint_range<tripoint> range( minp, maxp );
3442 
3443  std::vector<tripoint> escape_points;
3444 
3445  map &here = get_map();
3446  std::copy_if( range.begin(), range.end(), std::back_inserter( escape_points ),
3447  [&here]( const tripoint & elem ) {
3448  return here.passable( elem ) && here.has_floor_or_water( elem );
3449  } );
3450 
3451  cata::sort_by_rating( escape_points.begin(), escape_points.end(), [&]( const tripoint & elem ) {
3452  const int danger = std::accumulate( spheres.begin(), spheres.end(), 0,
3453  [&]( const int sum, const sphere & s ) {
3454  return sum + std::max( s.radius - rl_dist( elem, s.center ), 0 );
3455  } );
3456 
3457  const int distance = rl_dist( pos(), elem );
3458  const int move_cost = here.move_cost( elem );
3459 
3460  return std::make_tuple( danger, distance, move_cost );
3461  } );
3462 
3463  for( const tripoint &elem : escape_points ) {
3464  update_path( elem, no_bashing );
3465 
3466  if( elem == pos() || !path.empty() ) {
3467  break;
3468  }
3469  }
3470 
3471  if( !path.empty() ) {
3472  move_to_next();
3473  } else {
3474  move_pause();
3475  }
3476 }
void sort_by_rating(Iterator begin, Iterator end, RatingFunction rating_func)
Sort elements of a sequence by their rating (the smaller the better).
Definition: cata_algo.h:26
Definition: point.h:274

References tripoint_range< Tripoint >::begin(), tripoint_range< Tripoint >::end(), get_map(), max(), min(), map::move_cost(), move_cost, Creature::pos(), rl_dist(), cata::sort_by_rating(), tripoint::x, and tripoint::y.

◆ move_away_from() [2/2]

void npc::move_away_from ( const tripoint p,
bool  no_bash_atk = false,
std::set< tripoint > *  nomove = nullptr 
)

Definition at line 3222 of file npcmove.cpp.

3223 {
3224  tripoint best_pos = pos();
3225  int best = -1;
3226  int chance = 2;
3227  map &here = get_map();
3228  for( const tripoint &p : here.points_in_radius( pos(), 1 ) ) {
3229  if( nomove != nullptr && nomove->find( p ) != nomove->end() ) {
3230  continue;
3231  }
3232 
3233  if( p == pos() ) {
3234  continue;
3235  }
3236 
3237  if( p == get_player_character().pos() ) {
3238  continue;
3239  }
3240 
3241  const int cost = here.combined_movecost( pos(), p );
3242  if( cost <= 0 ) {
3243  continue;
3244  }
3245 
3246  const int dst = std::abs( p.x - pt.x ) + std::abs( p.y - pt.y ) + std::abs( p.z - pt.z );
3247  const int val = dst * 1000 / cost;
3248  if( val > best && can_move_to( p, no_bash_atk ) ) {
3249  best_pos = p;
3250  best = val;
3251  chance = 2;
3252  } else if( ( val == best && one_in( chance ) ) && can_move_to( p, no_bash_atk ) ) {
3253  best_pos = p;
3254  best = val;
3255  chance++;
3256  }
3257  }
3258 
3259  move_to( best_pos, no_bash_atk, nomove );
3260 }
int combined_movecost(const tripoint &from, const tripoint &to, const vehicle *ignored_vehicle=nullptr, int modifier=0, bool flying=false, bool via_ramp=false) const
Cost to move out of one tile and into the next.
Definition: map.cpp:2519
double abs(std::vector< double > const &params)

References abs(), can_move_to(), map::combined_movecost(), get_map(), get_player_character(), move_to(), one_in(), map::points_in_radius(), Creature::pos(), tripoint::x, tripoint::y, and tripoint::z.

Referenced by escape_explosion(), move_to(), game::npc_menu(), and game::vertical_move().

◆ move_pause()

void npc::move_pause ( )

Definition at line 3372 of file npcmove.cpp.

3374 {
3375  // make sure we're using the best weapon
3376  if( calendar::once_every( 1_hours ) ) {
3378  for( const bionic_id &bio_id : health_cbms ) {
3379  activate_bionic_by_id( bio_id );
3380  }
3381  if( wield_better_weapon() ) {
3382  return;
3383  }
3384  }
3385  // NPCs currently always aim when using a gun, even with no target
3386  // This simulates them aiming at stuff just at the edge of their range
3387  if( !get_wielded_item() || !get_wielded_item()->is_gun() ) {
3388  pause();
3389  return;
3390  }
3391 
3392  // Stop, drop, and roll
3393  if( has_effect( effect_onfire ) ) {
3394  pause();
3395  } else {
3396  aim( Target_attributes() );
3397  moves = std::min( moves, 0 );
3398  }
3399 }
void pause()
bool wield_better_weapon()
Definition: npcmove.cpp:4111
const std::vector< bionic_id > health_cbms
Definition: npcmove.cpp:202
static const efftype_id effect_onfire("onfire")

References activate_bionic_by_id(), aim(), bio_soporific, deactivate_bionic_by_id(), effect_onfire, Character::get_wielded_item(), Creature::has_effect(), anonymous_namespace{npcmove.cpp}::health_cbms, min(), Creature::moves, calendar::once_every(), Character::pause(), and wield_better_weapon().

Referenced by alt_attack(), avoid_friendly_fire(), execute_action(), go_to_omt_destination(), move_to(), move_to_next(), pick_up_item(), npc_attack_melee::use(), npc_attack_gun::use(), npc_attack_throw::use(), use_painkiller(), and worker_downtime().

◆ move_to()

void npc::move_to ( const tripoint p,
bool  no_bashing = false,
std::set< tripoint > *  nomove = nullptr 
)
NPC Dexterity increases chance to climb CLIMBABLE furniture or terrain

Definition at line 2882 of file npcmove.cpp.

2883 {
2884  tripoint p = pt;
2885  map &here = get_map();
2886  if( sees_dangerous_field( p )
2887  || ( nomove != nullptr && nomove->find( p ) != nomove->end() ) ) {
2888  // Move to a neighbor field instead, if possible.
2889  // Maybe this code already exists somewhere?
2890  auto other_points = here.get_dir_circle( pos(), p );
2891  for( const tripoint &ot : other_points ) {
2892  if( could_move_onto( ot )
2893  && ( nomove == nullptr || nomove->find( ot ) == nomove->end() ) ) {
2894 
2895  p = ot;
2896  break;
2897  }
2898  }
2899  }
2900 
2901  if( here.veh_at( p ).part_with_feature( VPFLAG_CARGO, true ) && !move_in_vehicle( this, p ) ) {
2902  auto other_points = here.get_dir_circle( pos(), p );
2903  for( const tripoint &ot : other_points ) {
2904  if( could_move_onto( ot ) && ( nomove == nullptr || nomove->find( ot ) == nomove->end() ) ) {
2905  p = ot;
2906  break;
2907  } else {
2908  path.clear();
2909  move_pause();
2910  return;
2911  }
2912  }
2913  }
2914 
2915  recoil = MAX_RECOIL;
2916 
2918  p.x = rng( posx() - 1, posx() + 1 );
2919  p.y = rng( posy() - 1, posy() + 1 );
2920  p.z = posz();
2921  }
2922 
2923  // nomove is used to resolve recursive invocation, so reset destination no
2924  // matter it was changed by stunned effect or not.
2925  if( nomove != nullptr && nomove->find( p ) != nomove->end() ) {
2926  p = pos();
2927  }
2928 
2929  // "Long steps" are allowed when crossing z-levels
2930  // Stairs teleport the player too
2931  if( rl_dist( pos(), p ) > 1 && p.z == posz() ) {
2932  // On the same level? Not so much. Something weird happened
2933  path.clear();
2934  move_pause();
2935  }
2936  creature_tracker &creatures = get_creature_tracker();
2937  bool attacking = false;
2938  if( creatures.creature_at<monster>( p ) ) {
2939  attacking = true;
2940  }
2941  if( !move_effects( attacking ) ) {
2942  mod_moves( -get_speed() );
2943  return;
2944  }
2945 
2946  Creature *critter = creatures.creature_at( p );
2947  if( critter != nullptr ) {
2948  if( critter == this ) { // We're just pausing!
2949  move_pause();
2950  return;
2951  }
2952  const Creature::Attitude att = attitude_to( *critter );
2953  if( att == Attitude::HOSTILE ) {
2954  if( !no_bashing ) {
2955  warn_about( "cant_flee", 5_turns + rng( 0, 5 ) * 1_turns );
2956  melee_attack( *critter, true );
2957  } else {
2958  move_pause();
2959  }
2960 
2961  return;
2962  }
2963 
2964  if( critter->is_avatar() ) {
2965  if( sees( *critter ) ) {
2966  say( chat_snippets().snip_let_me_pass.translated() );
2967  } else {
2968  stumble_invis( *critter );
2969  }
2970  }
2971 
2972  // Let NPCs push each other when non-hostile
2973  // TODO: Have them attack each other when hostile
2974  npc *np = dynamic_cast<npc *>( critter );
2975  if( np != nullptr && !np->in_sleep_state() ) {
2976  std::unique_ptr<std::set<tripoint>> newnomove;
2977  std::set<tripoint> *realnomove;
2978  if( nomove != nullptr ) {
2979  realnomove = nomove;
2980  } else {
2981  // create the no-move list
2982  newnomove = std::make_unique<std::set<tripoint>>();
2983  realnomove = newnomove.get();
2984  }
2985  // other npcs should not try to move into this npc anymore,
2986  // so infinite loop can be avoided.
2987  realnomove->insert( pos() );
2988  say( chat_snippets().snip_let_me_pass.translated() );
2989  np->move_away_from( pos(), true, realnomove );
2990  // if we moved NPC, readjust their path, so NPCs don't jostle each other out of their activity paths.
2991  if( np->attitude == NPCATT_ACTIVITY ) {
2992  std::vector<tripoint_bub_ms> activity_route = np->get_auto_move_route();
2993  if( !activity_route.empty() && !np->has_destination_activity() ) {
2994  tripoint_bub_ms final_destination;
2995  if( destination_point ) {
2996  final_destination = here.bub_from_abs( *destination_point );
2997  } else {
2998  final_destination = activity_route.back();
2999  }
3000  // TODO: fix point types
3001  np->update_path( final_destination.raw() );
3002  }
3003  }
3004  }
3005 
3006  if( critter->pos() == p ) {
3007  move_pause();
3008  return;
3009  }
3010  }
3011 
3012  // Boarding moving vehicles is fine, unboarding isn't
3013  bool moved = false;
3014  if( const optional_vpart_position vp = here.veh_at( pos() ) ) {
3015  const optional_vpart_position ovp = here.veh_at( p );
3016  if( vp->vehicle().is_moving() &&
3017  ( veh_pointer_or_null( ovp ) != veh_pointer_or_null( vp ) ||
3018  !ovp.part_with_feature( VPFLAG_BOARDABLE, true ) ) ) {
3019  move_pause();
3020  return;
3021  }
3022  }
3023 
3024  Character &player_character = get_player_character();
3025  if( p.z != posz() ) {
3026  // Z-level move
3027  // For now just teleport to the destination
3028  // TODO: Make it properly find the tile to move to
3029  if( is_mounted() ) {
3030  move_pause();
3031  return;
3032  }
3033  mod_moves( -get_speed() );
3034  moved = true;
3036  here.has_field_at( p, field_fd_last_known ) && !sees( player_character ) &&
3037  attitude_to( player_character ) == Attitude::HOSTILE ) {
3038  attack_air( p );
3039  move_pause();
3040  } else if( here.passable( p ) && !here.has_flag( ter_furn_flag::TFLAG_DOOR, p ) ) {
3041  bool diag = trigdist && posx() != p.x && posy() != p.y;
3042  if( is_mounted() ) {
3043  const double base_moves = run_cost( here.combined_movecost( pos(), p ),
3044  diag ) * 100.0 / mounted_creature->get_speed();
3045  const double encumb_moves = get_weight() / 4800.0_gram;
3046  mod_moves( -static_cast<int>( std::ceil( base_moves + encumb_moves ) ) );
3047  if( mounted_creature->has_flag( mon_flag_RIDEABLE_MECH ) ) {
3048  mounted_creature->use_mech_power( 1_kJ );
3049  }
3050  } else {
3051  mod_moves( -run_cost( here.combined_movecost( pos(), p ), diag ) );
3052  }
3053  moved = true;
3054  } else if( here.open_door( *this, p, !here.is_outside( pos() ), true ) ) {
3055  if( !is_hallucination() ) { // hallucinations don't open doors
3056  here.open_door( *this, p, !here.is_outside( pos() ) );
3057  mod_moves( -get_speed() );
3058  } else { // hallucinations teleport through doors
3059  mod_moves( -get_speed() );
3060  moved = true;
3061  }
3062  } else if( doors::can_unlock_door( here, *this, tripoint_bub_ms( pt ) ) ) {
3063  if( !is_hallucination() ) {
3064  doors::unlock_door( here, *this, tripoint_bub_ms( pt ) );
3065  } else {
3066  mod_moves( -get_speed() );
3067  moved = true;
3068  }
3069  } else if( get_dex() > 1 && here.has_flag_ter_or_furn( ter_furn_flag::TFLAG_CLIMBABLE, p ) ) {
3070  ///\EFFECT_DEX_NPC increases chance to climb CLIMBABLE furniture or terrain
3071  int climb = get_dex();
3072  if( one_in( climb ) ) {
3073  add_msg_if_npc( m_neutral, _( "%1$s tries to climb the %2$s but slips." ), get_name(),
3074  here.tername( p ) );
3075  mod_moves( -get_speed() * 4 );
3076  } else {
3077  add_msg_if_npc( m_neutral, _( "%1$s climbs over the %2$s." ), get_name(), here.tername( p ) );
3078  mod_moves( ( -get_speed() * 5 ) - ( rng( 0, climb ) * 20 ) );
3079  moved = true;
3080  }
3081  } else if( !no_bashing && smash_ability() > 0 && here.is_bashable( p ) &&
3082  here.bash_rating( smash_ability(), p ) > 0 ) {
3083  mod_moves( -get_speed() * 0.8 );
3084  here.bash( p, smash_ability() );
3085  } else {
3086  if( attitude == NPCATT_MUG ||
3087  attitude == NPCATT_KILL ||
3090  }
3091 
3092  set_moves( 0 );
3093  }
3094 
3095  if( moved ) {
3097  const tripoint old_pos = pos();
3098  setpos( p );
3099  if( old_pos.x - p.x < 0 ) {
3101  } else {
3103  }
3104  if( is_mounted() ) {
3105  if( mounted_creature->pos() != pos() ) {
3106  mounted_creature->setpos( pos() );
3107  mounted_creature->facing = facing;
3108  mounted_creature->process_triggers();
3111  }
3112  }
3114  !here.has_vehicle_floor( pos_bub() ) ) {
3115  add_effect( effect_bouldering, 1_turns, true );
3116  } else if( has_effect( effect_bouldering ) ) {
3118  }
3119 
3121  add_effect( effect_no_sight, 1_turns, true );
3122  } else if( has_effect( effect_no_sight ) ) {
3124  }
3125 
3126  if( in_vehicle ) {
3127  here.unboard_vehicle( old_pos );
3128  }
3129 
3130  // Close doors behind self (if you can)
3132  doors::close_door( here, *this, tripoint_bub_ms( old_pos ) );
3133  }
3134  // Lock doors as well
3136  doors::lock_door( here, *this, tripoint_bub_ms( old_pos ) );
3137  }
3138 
3139  if( here.veh_at( p ).part_with_feature( VPFLAG_BOARDABLE, true ) ) {
3140  here.board_vehicle( p, this );
3141  }
3142  here.creature_on_trap( *this );
3143  here.creature_in_field( *this );
3144  }
3145 }
units::mass get_weight() const override
Returns body weight plus weight of inventory and worn/wielded items.
Definition: character.cpp:3889
void make_footstep_noise() const
Definition: character.cpp:2235
bool move_effects(bool attacking) override
Processes effects which may prevent the Character from moving (bear traps, crushed,...
int run_cost(int base_cost, bool diag=false) const
Returns the player's modified base movement cost.
FacingDirection facing
return the direction the creature is facing, for sdl horizontal flip
Definition: creature.h:303
bool attack_air(const tripoint &p)
Definition: creature.cpp:1415
bool stumble_invis(const Creature &player, bool stumblemsg=true)
Definition: creature.cpp:1389
int posy() const
Definition: creature.h:314
void setpos(const tripoint &p)
Definition: creature.cpp:188
int posx() const
Definition: creature.h:311
std::vector< tripoint > get_dir_circle(const tripoint &f, const tripoint &t) const
Calculate next search points surrounding the current position.
Definition: map.cpp:7845
bool has_flag_ter_or_furn(const std::string &flag, const tripoint &p) const
Definition: map.cpp:3122
std::string tername(const tripoint &p) const
Definition: map.cpp:2340
bool has_vehicle_floor(const tripoint &p) const
Definition: map.cpp:2739
bool is_bashable(const tripoint &p, bool allow_floor=false) const
Returns true if there is a bashable vehicle part or the furn/terrain is bashable at p.
Definition: map.cpp:3240
void creature_in_field(Creature &critter)
Apply field effects to the creature when it's on a square with fields.
Definition: map_field.cpp:1745
bool has_field_at(const tripoint &p, bool check_bounds=true) const
Definition: map.cpp:6487
bash_params bash(const tripoint &p, int str, bool silent=false, bool destroy=false, bool bash_floor=false, const vehicle *bashing_vehicle=nullptr)
Returns a pair where first is whether anything was smashed and second is if it was destroyed.
Definition: map.cpp:4292
void creature_on_trap(Creature &critter, bool may_avoid=true) const
Apply trap effects to the creature, similar to creature_in_field.
Definition: map.cpp:9887
void board_vehicle(const tripoint &p, Character *pl)
Definition: map.cpp:1361
void add_msg_if_npc(const std::string &msg) const override
Definition: npc.cpp:3015
@ m_neutral
Definition: enums.h:354
bool trigdist
Definition: line.cpp:18
double ceil(std::vector< double > const &params)
mon_flag_id mon_flag_RIDEABLE_MECH
Definition: mtype.cpp:142
bool unlock_door(map &m, Creature &who, const tripoint_bub_ms &lockp)
Unlocks a door at "lockp" as "who.".
Definition: gates.cpp:409
void close_door(map &m, Creature &who, const tripoint_bub_ms &closep)
Handles deducting moves, printing messages (only non-NPCs cause messages), actually closing it,...
Definition: gates.cpp:254
bool lock_door(map &m, Creature &who, const tripoint_bub_ms &lockp)
Locks a door at "lockp" as "who.".
Definition: gates.cpp:356
static const field_type_str_id field_fd_last_known("fd_last_known")
static const efftype_id effect_bouldering("bouldering")
static const efftype_id effect_stunned("stunned")
static const efftype_id effect_stumbled_into_invisible("stumbled_into_invisible")
static const efftype_id effect_psi_stunned("psi_stunned")
static const efftype_id effect_no_sight("no_sight")

References _, Creature::add_effect(), add_msg_if_npc(), Creature::attack_air(), attitude, attitude_to(), map::bash(), map::bash_rating(), map::board_vehicle(), map::bub_from_abs(), doors::can_unlock_door(), ceil(), chat_snippets(), doors::close_door(), close_doors, map::combined_movecost(), could_move_onto(), creature_tracker::creature_at(), map::creature_in_field(), map::creature_on_trap(), Character::destination_point, effect_bouldering, effect_no_sight, effect_psi_stunned, effect_stumbled_into_invisible, effect_stunned, Creature::facing, field_fd_last_known, Character::get_auto_move_route(), get_creature_tracker(), Character::get_dex(), map::get_dir_circle(), get_map(), Character::get_name(), get_player_character(), Character::get_speed(), Character::get_weight(), Character::has_destination_activity(), Creature::has_effect(), map::has_field_at(), npc_follower_rules::has_flag(), map::has_flag(), map::has_flag_ter_or_furn(), map::has_vehicle_floor(), Creature::HOSTILE, Character::in_sleep_state(), Character::in_vehicle, Creature::is_avatar(), map::is_bashable(), is_hallucination(), Character::is_mounted(), map::is_outside(), is_player_ally(), LEFT, doors::lock_door(), lock_doors, m_neutral, Character::make_footstep_noise(), MAX_RECOIL, Character::melee_attack(), Creature::mod_moves(), mon_flag_RIDEABLE_MECH, Character::mounted_creature, move_away_from(), Character::move_effects(), Character::move_in_vehicle(), move_pause(), NPCATT_ACTIVITY, NPCATT_FLEE_TEMP, NPCATT_KILL, NPCATT_MUG, NPCATT_WAIT_FOR_LEAVE, one_in(), map::open_door(), optional_vpart_position::part_with_feature(), map::passable(), path, Creature::pos(), Creature::pos_bub(), Creature::posx(), Creature::posy(), Creature::posz(), coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), Character::recoil, Creature::remove_effect(), RIGHT, rl_dist(), rng(), rules, Character::run_cost(), say(), Character::sees(), sees_dangerous_field(), set_attitude(), Creature::set_moves(), Creature::setpos(), smash_ability(), Creature::stumble_invis(), map::tername(), TFLAG_CLIMBABLE, TFLAG_DOOR, TFLAG_NO_SIGHT, TFLAG_UNSTABLE, trigdist, map::unboard_vehicle(), doors::unlock_door(), update_path(), map::veh_at(), veh_pointer_or_null(), VPFLAG_BOARDABLE, VPFLAG_CARGO, warn_about(), tripoint::x, tripoint::y, and tripoint::z.

Referenced by avoid_friendly_fire(), execute_action(), move(), move_away_from(), and move_to_next().

◆ move_to_next()

void npc::move_to_next ( )

Definition at line 3148 of file npcmove.cpp.

3149 {
3150  while( !path.empty() && pos() == path[0] ) {
3151  path.erase( path.begin() );
3152  }
3153 
3154  if( path.empty() ) {
3155  add_msg_debug( debugmode::DF_NPC, "npc::move_to_next() called with an empty path or path "
3156  "containing only current position" );
3157  move_pause();
3158  return;
3159  }
3160 
3161  move_to( path[0] );
3162  if( !path.empty() && pos() == path[0] ) { // Move was successful
3163  path.erase( path.begin() );
3164  }
3165 }

References add_msg_debug, debugmode::DF_NPC, move_pause(), move_to(), path, and Creature::pos().

Referenced by address_needs(), alt_attack(), execute_action(), go_to_omt_destination(), heal_player(), look_for_player(), move(), mug_player(), pick_up_item(), reach_omt_destination(), npc_attack_melee::use(), and worker_downtime().

◆ mug_player()

void npc::mug_player ( Character mark)

Definition at line 4660 of file npcmove.cpp.

4661 {
4662  if( mark.is_armed() ) {
4663  make_angry();
4664  }
4665 
4666  if( rl_dist( pos(), mark.pos() ) > 1 ) { // We have to travel
4667  update_path( mark.pos() );
4668  move_to_next();
4669  return;
4670  }
4671 
4672  Character &player_character = get_player_character();
4673  const bool u_see = player_character.sees( *this ) || player_character.sees( mark );
4674  if( mark.cash > 0 ) {
4675  if( !is_hallucination() ) { // hallucinations can't take items
4676  cash += mark.cash;
4677  mark.cash = 0;
4678  }
4679  set_moves( 0 );
4680  // Describe the action
4681  if( mark.is_npc() ) {
4682  if( u_see ) {
4683  add_msg( _( "%1$s takes %2$s's money!" ), get_name(), mark.get_name() );
4684  }
4685  } else {
4686  add_msg( m_bad, _( "%s takes your money!" ), get_name() );
4687  }
4688  return;
4689  }
4690 
4691  // We already have their money; take some goodies!
4692  // value_mod affects at what point we "take the money and run"
4693  // A lower value means we'll take more stuff
4694  double value_mod = 1 - ( ( 10 - personality.bravery ) * .05 ) -
4695  ( ( 10 - personality.aggression ) * .04 ) -
4696  ( ( 10 - personality.collector ) * .06 );
4697  if( !mark.is_npc() ) {
4698  value_mod += ( op_of_u.fear * .08 );
4699  value_mod -= ( ( 8 - op_of_u.value ) * .07 );
4700  }
4701  double best_value = minimum_item_value() * value_mod;
4702  item *to_steal = nullptr;
4703  std::vector<const item *> pseudo_items = mark.get_pseudo_items();
4704  const auto inv_valuables = mark.items_with( [this, pseudo_items]( const item & itm ) {
4705  return std::find( pseudo_items.begin(), pseudo_items.end(), &itm ) == pseudo_items.end() &&
4706  value( itm ) > 0;
4707  } );
4708  for( item *it : inv_valuables ) {
4709  item &front_stack = *it; // is this safe?
4710  if( value( front_stack ) >= best_value &&
4711  can_pickVolume( front_stack, true ) &&
4712  can_pickWeight( front_stack, true ) ) {
4713  best_value = value( front_stack );
4714  to_steal = &front_stack;
4715  }
4716  }
4717  if( to_steal == nullptr ) { // Didn't find anything worthwhile!
4719  if( !one_in( 3 ) ) {
4720  say( chat_snippets().snip_done_mugging.translated() );
4721  }
4722  mod_moves( -get_speed() );
4723  return;
4724  }
4725  item stolen;
4726  if( !is_hallucination() ) {
4727  stolen = mark.i_rem( to_steal );
4728  i_add( stolen );
4729  }
4730  if( mark.is_npc() ) {
4731  if( u_see ) {
4732  add_msg( _( "%1$s takes %2$s's %3$s." ), get_name(), mark.get_name(), stolen.tname() );
4733  }
4734  } else {
4735  add_msg( m_bad, _( "%1$s takes your %2$s." ), get_name(), stolen.tname() );
4736  }
4737  mod_moves( -get_speed() );
4738  if( !mark.is_npc() ) {
4739  op_of_u.value -= rng( 0, 1 ); // Decrease the value of the player
4740  }
4741 }
std::vector< const item * > get_pseudo_items() const
Definition: character.cpp:2666
bool can_pickWeight(const item &it, bool safe=true) const
Definition: character.cpp:3251
bool can_pickVolume(const item &it, bool safe=false, const item *avoid=nullptr, bool ignore_pkt_settings=true) const
Definition: character.cpp:3222
std::vector< const item * > pseudo_items
Definition: character.h:4075
item_location i_add(item it, bool should_stack=true, const item *avoid=nullptr, const item *original_inventory_item=nullptr, bool allow_drop=true, bool allow_wield=true, bool ignore_pkt_settings=false)
Adds the item to the character's worn items or wields it, or prompts if the Character cannot pick it ...
void make_angry()
Definition: npc.cpp:1626

References _, add_msg(), npc_personality::aggression, npc_personality::bravery, Character::can_pickVolume(), Character::can_pickWeight(), Character::cash, chat_snippets(), npc_personality::collector, npc_opinion::fear, Character::get_name(), get_player_character(), Character::get_pseudo_items(), Character::get_speed(), Character::i_add(), Character::i_rem(), Character::is_armed(), is_hallucination(), Character::is_npc(), visitable::items_with(), m_bad, make_angry(), minimum_item_value(), Creature::mod_moves(), move_to_next(), NPCATT_FLEE_TEMP, one_in(), op_of_u, personality, Creature::pos(), Character::pseudo_items, rl_dist(), rng(), say(), Character::sees(), set_attitude(), Creature::set_moves(), item::tname(), update_path(), npc_opinion::value, and value().

Referenced by execute_action().

◆ mutiny()

void npc::mutiny ( )

Definition at line 1540 of file npc.cpp.

1541 {
1542  if( !my_fac || !is_player_ally() ) {
1543  return;
1544  }
1545  const bool seen = get_player_view().sees( pos() );
1546  if( seen ) {
1547  add_msg( m_bad, _( "%s is tired of your incompetent leadership and abuse!" ), disp_name() );
1548  }
1549  // NPCs leaving your faction due to mistreatment further reduce their opinion of you
1550  if( my_fac->likes_u < -10 ) {
1551  op_of_u.trust += my_fac->respects_u / 10;
1552  op_of_u.anger += my_fac->likes_u / 10;
1553  }
1554  // NPCs leaving your faction for abuse reduce the hatred your (remaining) followers
1555  // feel for you, but also reduces their respect for you.
1556  my_fac->likes_u = std::max( 0, my_fac->likes_u / 2 + 10 );
1557  my_fac->respects_u -= 5;
1558  my_fac->trusts_u -= 5;
1559  g->remove_npc_follower( getID() );
1560  set_fac( faction_amf );
1562  if( assigned_camp ) {
1563  assigned_camp = std::nullopt;
1564  }
1567  say( _( "<follower_mutiny> Adios, motherfucker!" ), sounds::sound_t::order );
1568  if( seen ) {
1569  my_fac->known_by_u = true;
1570  }
1571 }
void clear_all_priorities()
Definition: npc.cpp:177

References _, add_msg(), npc_opinion::anger, assigned_camp, chatbin, job_data::clear_all_priorities(), Character::disp_name(), faction_amf, dialogue_chatbin::first_topic, g, get_player_view(), Character::getID(), is_player_ally(), job, faction_template::known_by_u, faction_template::likes_u, m_bad, max(), Character::my_fac, NPCATT_NULL, op_of_u, sounds::order, Creature::pos(), faction_template::respects_u, say(), viewer::sees(), set_attitude(), set_fac(), dialogue_chatbin::talk_stranger_neutral, npc_opinion::trust, and faction_template::trusts_u.

Referenced by basecamp::feed_workers(), form_opinion(), make_angry(), and move().

◆ name_and_activity()

std::string npc::name_and_activity ( ) const

Definition at line 3771 of file npc.cpp.

3772 {
3773  if( current_activity_id ) {
3774  //~ %1$s - npc name, %2$s - npc current activity name.
3775  return string_format( _( "%1$s (%2$s)" ), get_name(), get_current_activity() );
3776  } else {
3777  return get_name();
3778  }
3779 }

References _, current_activity_id, get_current_activity(), Character::get_name(), and string_format().

Referenced by game::chat(), and name_and_maybe_activity().

◆ name_and_maybe_activity()

std::string npc::name_and_maybe_activity ( ) const
overridevirtual

Reimplemented from Character.

Definition at line 3781 of file npc.cpp.

3782 {
3783  return name_and_activity();
3784 }
std::string name_and_activity() const
Definition: npc.cpp:3771

References name_and_activity().

◆ npc_dismount()

void npc::npc_dismount ( )

Definition at line 2460 of file npc.cpp.

2461 {
2462  if( !mounted_creature || !has_effect( effect_riding ) ) {
2464  "NPC %s tried to dismount, but they have no mount, or they are not riding",
2465  disp_name() );
2466  return;
2467  }
2468  std::optional<tripoint> pnt;
2469  for( const tripoint &elem : get_map().points_in_radius( pos(), 1 ) ) {
2470  if( g->is_empty( elem ) ) {
2471  pnt = elem;
2472  break;
2473  }
2474  }
2475  if( !pnt ) {
2476  add_msg_debug( debugmode::DF_NPC, "NPC %s could not find a place to dismount.", disp_name() );
2477  return;
2478  }
2480  if( mounted_creature->has_flag( mon_flag_RIDEABLE_MECH ) &&
2481  !mounted_creature->type->mech_weapon.is_empty() ) {
2483  }
2484  mounted_creature->remove_effect( effect_ridden );
2485  mounted_creature->add_effect( effect_controlled, 5_turns );
2486  mounted_creature = nullptr;
2487  setpos( *pnt );
2488  mod_moves( -get_speed() );
2489 }
void remove_item()
Removes the selected item from the game.
tripoint_range< Tripoint > points_in_radius(const Tripoint &center, const int radius, const int radiusz=0)
Definition: map_iterator.h:154
static const efftype_id effect_riding("riding")
static const efftype_id effect_controlled("controlled")

References add_msg_debug, debugmode::DF_NPC, Character::disp_name(), effect_controlled, effect_ridden, effect_riding, g, get_map(), Character::get_speed(), Character::get_wielded_item(), Creature::has_effect(), Creature::mod_moves(), mon_flag_RIDEABLE_MECH, Character::mounted_creature, points_in_radius(), Creature::pos(), Creature::remove_effect(), item_location::remove_item(), and Creature::setpos().

Referenced by talk_function::dismount().

◆ npc_update_body()

void npc::npc_update_body ( )

Update body, but throttled.

Definition at line 3062 of file npc.cpp.

3063 {
3064  if( calendar::once_every( 10_seconds ) ) {
3067  }
3068 }
void update_body()
Updates all "biology" by one turn.

References Creature::last_updated, calendar::once_every(), calendar::turn, and Character::update_body().

◆ on_attacked()

void npc::on_attacked ( const Creature attacker)

Definition at line 1650 of file npc.cpp.

1651 {
1652  if( is_hallucination() ) {
1653  die( nullptr );
1654  }
1655  if( attacker.is_avatar() && !is_enemy() && !is_dead() && !guaranteed_hostile() ) {
1656  make_angry();
1657  hit_by_player = true;
1658  }
1659 }

References die(), guaranteed_hostile(), hit_by_player, Creature::is_avatar(), is_dead(), is_enemy(), is_hallucination(), and make_angry().

Referenced by monster::attack_at(), avatar::disarm(), game::npc_menu(), Character::on_hit(), projectile_attack(), avatar::steal(), and iuse::tazer().

◆ on_load()

void npc::on_load ( )

Retroactively update npc.

Definition at line 3070 of file npc.cpp.

3071 {
3072  const auto advance_effects = [&]( const time_duration & elapsed_dur ) {
3073  for( auto &elem : *effects ) {
3074  for( auto &_effect_it : elem.second ) {
3075  effect &e = _effect_it.second;
3076  const time_duration &time_left = e.get_duration();
3077  if( time_left > 1_turns ) {
3078  if( time_left < elapsed_dur ) {
3079  e.set_duration( 1_turns );
3080  } else {
3081  e.set_duration( time_left - elapsed_dur );
3082  }
3083  }
3084  }
3085  }
3086  };
3087  const auto advance_focus = [this]( const int minutes ) {
3088  // scale to match focus_pool magnitude
3089  const int equilibrium = 1000 * focus_equilibrium_sleepiness_cap( calc_focus_equilibrium() );
3090  const double focus_ratio = std::pow( 0.99, minutes );
3091  // Approximate new focus pool, every minute focus_pool contributes 99%, the remainder comes from equilibrium
3092  // This is pretty accurate as long as the equilibrium doesn't change too much during the period
3093  focus_pool = static_cast<int>( focus_ratio * focus_pool + ( 1 - focus_ratio ) * equilibrium );
3094  };
3095 
3096  // Cap at some reasonable number, say 2 days
3097  const time_duration dt = std::min( calendar::turn - last_updated, 2_days );
3098  // TODO: Sleeping, healing etc.
3100  time_point cur = calendar::turn - dt;
3101  add_msg_debug( debugmode::DF_NPC, "on_load() by %s, %d turns", get_name(), to_turns<int>( dt ) );
3102  // First update with 30 minute granularity, then 5 minutes, then turns
3103  for( ; cur < calendar::turn - 30_minutes; cur += 30_minutes + 1_turns ) {
3104  update_body( cur, cur + 30_minutes );
3105  advance_effects( 30_minutes );
3106  advance_focus( 30 );
3107  }
3108  for( ; cur < calendar::turn - 5_minutes; cur += 5_minutes + 1_turns ) {
3109  update_body( cur, cur + 5_minutes );
3110  advance_effects( 5_minutes );
3111  advance_focus( 5 );
3112  }
3113  for( ; cur < calendar::turn; cur += 1_turns ) {
3114  update_body( cur, cur + 1_turns );
3115  process_effects();
3116  if( ( cur - calendar::turn_zero ) % 1_minutes == 0_turns ) {
3118  }
3119  }
3120 
3121  if( dt > 0_turns ) {
3122  // This ensures food is properly rotten at load
3123  // Otherwise NPCs try to eat rotten food and fail
3124  process_items();
3125  // give NPCs that are doing activities a pile of moves
3126  if( has_destination() || activity ) {
3127  mod_moves( to_moves<int>( dt ) );
3128  }
3129  }
3130 
3131  // Not necessarily true, but it's not a bad idea to set this
3132  has_new_items = true;
3133 
3134  map &here = get_map();
3135  // for spawned npcs
3137  !here.has_vehicle_floor( pos_bub() ) ) {
3138  add_effect( effect_bouldering, 1_turns, true );
3139  } else if( has_effect( effect_bouldering ) ) {
3141  }
3142  if( here.veh_at( pos() ).part_with_feature( VPFLAG_BOARDABLE, true ) && !in_vehicle ) {
3143  here.board_vehicle( pos(), this );
3144  }
3146  if( const monster *const mon = get_creature_tracker().creature_at<monster>( pos() ) ) {
3147  mounted_creature = g->shared_from( *mon );
3148  } else {
3150  "NPC is meant to be riding, though the mount is not found when %s is loaded",
3151  disp_name() );
3152  }
3153  }
3154  if( has_trait( trait_HALLUCINATION ) ) {
3155  hallucination = true;
3156  }
3158  shop_restock();
3159 }
int focus_equilibrium_sleepiness_cap(int equilibrium) const
Returns focus equilibrium cap due to sleepiness.
Definition: character.cpp:3690
int focus_pool
Definition: character.h:2757
int calc_focus_equilibrium(bool ignore_pain=false) const
Uses morale and other factors to return the character's focus target goto value.
Definition: character.cpp:3704
void process_items()
void update_mental_focus()
Uses calc_focus_change to update the character's current focus.
Definition: character.cpp:3781
void process_effects() override
Processes human-specific effects of effects before calling Creature::process_effects().
time_duration get_duration() const
Returns the remaining duration of an effect.
Definition: effect.cpp:1068
void set_duration(const time_duration &dur, bool alert=false)
Sets the duration, capping at max duration.
Definition: effect.cpp:1076
void shop_restock()
Definition: npc.cpp:1933
void load_existing_character(Character &you)
Load any new eocs that don't exist in the save.
static const trait_id trait_HALLUCINATION("HALLUCINATION")
static const efftype_id effect_bouldering("bouldering")

References Character::activity, Creature::add_effect(), add_msg_debug, map::board_vehicle(), Character::calc_focus_equilibrium(), debugmode::DF_NPC, Character::disp_name(), effect_bouldering, effect_riding, Creature::effects, Character::focus_equilibrium_sleepiness_cap(), Character::focus_pool, g, get_creature_tracker(), effect::get_duration(), get_map(), Character::get_name(), hallucination, Character::has_destination(), Creature::has_effect(), map::has_flag(), has_new_items, Character::has_trait(), map::has_vehicle_floor(), Character::in_vehicle, Creature::last_updated, effect_on_conditions::load_existing_character(), min(), Creature::mod_moves(), Character::mounted_creature, Creature::pos(), Creature::pos_bub(), Character::process_effects(), Character::process_items(), Creature::remove_effect(), effect::set_duration(), shop_restock(), TFLAG_UNSTABLE, trait_HALLUCINATION, calendar::turn, calendar::turn_zero, Character::update_body(), Character::update_mental_focus(), map::veh_at(), and VPFLAG_BOARDABLE.

Referenced by game::load_npcs().

◆ on_move()

void npc::on_move ( const tripoint_abs_ms old_pos)
overrideprotectedvirtual

Reimplemented from Character.

Definition at line 960 of file npc.cpp.

961 {
962  Character::on_move( old_pos );
963  const point_abs_om pos_om_old = project_to<coords::om>( old_pos.xy() );
964  const point_abs_om pos_om_new = project_to<coords::om>( get_location().xy() );
965  if( !is_fake() && pos_om_old != pos_om_new ) {
966  overmap &om_old = overmap_buffer.get( pos_om_old );
967  overmap &om_new = overmap_buffer.get( pos_om_new );
968  if( !unique_id.empty() ) {
969  g->update_unique_npc_location( unique_id, pos_om_new );
970  }
971  if( const auto ptr = om_old.erase_npc( getID() ) ) {
972  om_new.insert_npc( ptr );
973  } else {
974  // Don't move the npc pointer around to avoid having two overmaps
975  // with the same npc pointer
976  debugmsg( "could not find npc %s on its old overmap", get_name() );
977  }
978  }
979 }
void on_move(const tripoint_abs_ms &old_pos) override
Definition: character.cpp:3072
shared_ptr_fast< npc > erase_npc(const character_id &id)
Removes the npc and returns it ( or returns nullptr if not found ).
Definition: overmap.cpp:3082
void insert_npc(const shared_ptr_fast< npc > &who)
Adds the npc to the contained list of npcs ( npcs ).
Definition: overmap.cpp:3076
overmap & get(const point_abs_om &)
Uses overmap coordinates, that means x and y are directly compared with the position of the overmap.

References debugmsg, overmap::erase_npc(), g, overmapbuffer::get(), Creature::get_location(), Character::get_name(), Character::getID(), overmap::insert_npc(), Creature::is_fake(), Character::on_move(), overmap_buffer, unique_id, and coords::coord_point< Point, Origin, Scale, InBounds >::xy().

◆ on_unload()

void npc::on_unload ( )

Do some cleanup and caching as npc is being unloaded from map.

Definition at line 3057 of file npc.cpp.

3058 {
3059 }

Referenced by game::unload_npcs().

◆ operator=() [1/2]

npc& npc::operator= ( const npc )
delete

◆ operator=() [2/2]

npc & npc::operator= ( npc &&  )
defaultnoexcept

◆ opinion_text()

std::string npc::opinion_text ( ) const

Definition at line 2651 of file npc.cpp.

2652 {
2653  std::string ret;
2654  std::string desc;
2655 
2656  if( op_of_u.trust <= -10 ) {
2657  desc = _( "Completely untrusting" );
2658  } else if( op_of_u.trust <= -6 ) {
2659  desc = _( "Very untrusting" );
2660  } else if( op_of_u.trust <= -3 ) {
2661  desc = _( "Untrusting" );
2662  } else if( op_of_u.trust <= 2 ) {
2663  desc = _( "Uneasy" );
2664  } else if( op_of_u.trust <= 4 ) {
2665  desc = _( "Trusting" );
2666  } else if( op_of_u.trust < 10 ) {
2667  desc = _( "Very trusting" );
2668  } else {
2669  desc = _( "Completely trusting" );
2670  }
2671 
2672  ret += string_format( _( "Trust: %d (%s);\n" ), op_of_u.trust, desc );
2673 
2674  if( op_of_u.fear <= -10 ) {
2675  desc = _( "Thinks you're laughably harmless" );
2676  } else if( op_of_u.fear <= -6 ) {
2677  desc = _( "Thinks you're harmless" );
2678  } else if( op_of_u.fear <= -3 ) {
2679  desc = _( "Unafraid" );
2680  } else if( op_of_u.fear <= 2 ) {
2681  desc = _( "Wary" );
2682  } else if( op_of_u.fear <= 5 ) {
2683  desc = _( "Afraid" );
2684  } else if( op_of_u.fear < 10 ) {
2685  desc = _( "Very afraid" );
2686  } else {
2687  desc = _( "Terrified" );
2688  }
2689 
2690  ret += string_format( _( "Fear: %d (%s);\n" ), op_of_u.fear, desc );
2691 
2692  if( op_of_u.value <= -10 ) {
2693  desc = _( "Considers you a major liability" );
2694  } else if( op_of_u.value <= -6 ) {
2695  desc = _( "Considers you a burden" );
2696  } else if( op_of_u.value <= -3 ) {
2697  desc = _( "Considers you an annoyance" );
2698  } else if( op_of_u.value <= 2 ) {
2699  desc = _( "Doesn't care about you" );
2700  } else if( op_of_u.value <= 5 ) {
2701  desc = _( "Values your presence" );
2702  } else if( op_of_u.value < 10 ) {
2703  desc = _( "Treasures you" );
2704  } else {
2705  desc = _( "Best Friends Forever!" );
2706  }
2707 
2708  ret += string_format( _( "Value: %d (%s);\n" ), op_of_u.value, desc );
2709 
2710  if( op_of_u.anger <= -10 ) {
2711  desc = _( "You can do no wrong!" );
2712  } else if( op_of_u.anger <= -6 ) {
2713  desc = _( "You're good people" );
2714  } else if( op_of_u.anger <= -3 ) {
2715  desc = _( "Thinks well of you" );
2716  } else if( op_of_u.anger <= 2 ) {
2717  desc = _( "Ambivalent" );
2718  } else if( op_of_u.anger <= 5 ) {
2719  desc = _( "Pissed off" );
2720  } else if( op_of_u.anger < 10 ) {
2721  desc = _( "Angry" );
2722  } else {
2723  desc = _( "About to kill you" );
2724  }
2725 
2726  ret += string_format( _( "Anger: %d (%s)." ), op_of_u.anger, desc );
2727 
2728  return ret;
2729 }

References _, npc_opinion::anger, npc_opinion::fear, op_of_u, cata::hash64_detail::ret, string_format(), npc_opinion::trust, and npc_opinion::value.

Referenced by talker_npc::opinion_text().

◆ patient_assessment()

healing_options npc::patient_assessment ( const Character c)

Definition at line 2381 of file npcmove.cpp.

2382 {
2383  healing_options try_to_fix;
2384  try_to_fix.clear_all();
2385 
2386  for( bodypart_id part_id : c.get_all_body_parts( get_body_part_flags::only_main ) ) {
2387  if( c.has_effect( effect_bleed, part_id ) ) {
2388  try_to_fix.bleed = true;
2389  }
2390  if( c.has_effect( effect_bite, part_id ) ) {
2391  try_to_fix.bite = true;
2392  }
2393  if( c.has_effect( effect_infected, part_id ) ) {
2394  try_to_fix.infect = true;
2395  }
2396 
2397  int part_threshold = 75;
2398  if( part_id.id() == body_part_head ) {
2399  part_threshold += 20;
2400  } else if( part_id.id() == body_part_torso ) {
2401  part_threshold += 10;
2402  }
2403  part_threshold = std::min( 80, part_threshold );
2404  part_threshold = part_threshold * c.get_part_hp_max( part_id ) / 100;
2405 
2406  if( c.get_part_hp_cur( part_id ) <= part_threshold ) {
2407  if( !c.has_effect( effect_bandaged, part_id ) ) {
2408  try_to_fix.bandage = true;
2409  }
2410  if( !c.has_effect( effect_disinfected, part_id ) ) {
2411  try_to_fix.disinfect = true;
2412  }
2413  }
2414  }
2415  return try_to_fix;
2416 }
const bodypart_str_id body_part_torso("torso")
const bodypart_str_id body_part_head("head")
static const efftype_id effect_bandaged("bandaged")
static const efftype_id effect_disinfected("disinfected")

References healing_options::bandage, healing_options::bite, healing_options::bleed, body_part_head, body_part_torso, c, healing_options::clear_all(), healing_options::disinfect, effect_bandaged, effect_bite, effect_bleed, effect_disinfected, effect_infected, healing_options::infect, min(), and only_main.

Referenced by address_needs().

◆ pick_talk_topic()

std::string npc::pick_talk_topic ( const Character u)

◆ pick_up_item()

void npc::pick_up_item ( )

Definition at line 3655 of file npcmove.cpp.

3656 {
3657  if( is_hallucination() ) {
3658  return;
3659  }
3660 
3662  add_msg_debug( debugmode::DF_NPC, "%s::pick_up_item(); Canceling on player's request", get_name() );
3663  fetching_item = false;
3664  wanted_item = {};
3665  mod_moves( -1 );
3666  return;
3667  }
3668 
3669  map &here = get_map();
3670  const std::optional<vpart_reference> vp = here.veh_at( wanted_item_pos ).part_with_feature(
3671  VPFLAG_CARGO, false );
3672  const bool has_cargo = vp && !vp->has_feature( "LOCKED" );
3673 
3674  if( ( !here.has_items( wanted_item_pos ) && !has_cargo &&
3676  ( is_player_ally() && g->check_zone( zone_type_NO_NPC_PICKUP, wanted_item_pos ) ) ) {
3677  // Items we wanted no longer exist and we can see it
3678  // Or player who is leading us doesn't want us to pick it up
3679  fetching_item = false;
3680  wanted_item = {};
3681  move_pause();
3682  add_msg_debug( debugmode::DF_NPC, "Canceling pickup - no items or new zone" );
3683  return;
3684  }
3685 
3686  // Check: Is the item owned? Has the situation changed since we last moved? Am 'I' now
3687  // standing in front of the shopkeeper/player that I am about to steal from?
3688  if( wanted_item ) {
3689  if( !::good_for_pickup( *wanted_item, *this, wanted_item_pos ) ) {
3691  "%s canceling pickup - situation changed since they decided to take item", get_name() );
3692  fetching_item = false;
3693  wanted_item = {};
3694  move_pause();
3695  return;
3696  }
3697  }
3698 
3699  add_msg_debug( debugmode::DF_NPC, "%s::pick_up_item(); [ % d, % d, % d] => [ % d, % d, % d]",
3700  get_name(),
3702  if( const std::optional<tripoint> dest = nearest_passable( wanted_item_pos, pos() ) ) {
3703  update_path( *dest );
3704  }
3705 
3706  const int dist_to_pickup = rl_dist( pos(), wanted_item_pos );
3707  if( dist_to_pickup > 1 && !path.empty() ) {
3708  add_msg_debug( debugmode::DF_NPC, "Moving; [%d, %d, %d] => [%d, %d, %d]",
3709  posx(), posy(), posz(), path[0].x, path[0].y, path[0].z );
3710 
3711  move_to_next();
3712  return;
3713  } else if( dist_to_pickup > 1 && path.empty() ) {
3714  add_msg_debug( debugmode::DF_NPC, "Can't find path" );
3715  // This can happen, always do something
3716  fetching_item = false;
3717  wanted_item = {};
3718  move_pause();
3719  return;
3720  }
3721 
3722  // We're adjacent to the item; grab it!
3723 
3724  auto picked_up = pick_up_item_map( wanted_item_pos );
3725  if( picked_up.empty() && has_cargo ) {
3726  picked_up = pick_up_item_vehicle( vp->vehicle(), vp->part_index() );
3727  }
3728 
3729  if( picked_up.empty() ) {
3730  // Last chance: plant harvest
3731  if( here.is_harvestable( wanted_item_pos ) ) {
3732  here.examine( *this, wanted_item_pos );
3733  // Note: we didn't actually pick up anything, just spawned items
3734  // but we want the item picker to find new items
3735  fetching_item = false;
3736  wanted_item = {};
3737  return;
3738  }
3739  }
3740  viewer &player_view = get_player_view();
3741  // Describe the pickup to the player
3742  bool u_see = player_view.sees( *this ) || player_view.sees( wanted_item_pos );
3743  if( u_see ) {
3744  if( picked_up.size() == 1 ) {
3745  add_msg( _( "%1$s picks up a %2$s." ), get_name(), picked_up.front().tname() );
3746  } else if( picked_up.size() == 2 ) {
3747  add_msg( _( "%1$s picks up a %2$s and a %3$s." ), get_name(), picked_up.front().tname(),
3748  picked_up.back().tname() );
3749  } else if( picked_up.size() > 2 ) {
3750  add_msg( _( "%s picks up several items." ), get_name() );
3751  } else {
3752  add_msg( _( "%s looks around nervously, as if searching for something." ), get_name() );
3753  }
3754  }
3755 
3756  for( item &it : picked_up ) {
3757  int itval = value( it );
3758  if( itval < worst_item_value ) {
3759  worst_item_value = itval;
3760  }
3761  i_add( it );
3762  mod_moves( -get_speed() );
3763  }
3764 
3765  fetching_item = false;
3766  wanted_item = {};
3767  has_new_items = true;
3768 }
bool is_harvestable(const tripoint &pos) const
Returns true if point at pos is harvestable right now, with no extra tools.
Definition: map.cpp:2217
bool has_items(const tripoint &p) const
Checks for existence of items.
Definition: map.cpp:5890
void examine(Character &you, const tripoint &pos) const
Calls the examine function of furniture or terrain at given tile, for given character.
Definition: map.cpp:2207
std::list< item > pick_up_item_map(const tripoint &where)
Picks up items and returns a list of them.
Definition: npcmove.cpp:3877
std::list< item > pick_up_item_vehicle(vehicle &veh, int part_index)
Definition: npcmove.cpp:3883

References _, add_msg(), add_msg_debug, allow_pick_up, debugmode::DF_NPC, debugmode::DF_NPC_ITEMAI, map::examine(), fetching_item, g, get_map(), Character::get_name(), get_player_view(), Character::get_speed(), anonymous_namespace{npcmove.cpp}::good_for_pickup(), npc_follower_rules::has_flag(), map::has_items(), has_new_items, Character::i_add(), is_hallucination(), map::is_harvestable(), is_player_ally(), Creature::mod_moves(), move_pause(), move_to_next(), nearest_passable(), optional_vpart_position::part_with_feature(), path, pick_up_item_map(), pick_up_item_vehicle(), Creature::pos(), Creature::posx(), Creature::posy(), Creature::posz(), rl_dist(), rules, Character::sees(), viewer::sees(), update_path(), value(), map::veh_at(), VPFLAG_CARGO, wanted_item, wanted_item_pos, worst_item_value, tripoint::x, tripoint::y, tripoint::z, and zone_type_NO_NPC_PICKUP.

Referenced by execute_action().

◆ pick_up_item_map()

std::list< item > npc::pick_up_item_map ( const tripoint where)

Picks up items and returns a list of them.

Definition at line 3877 of file npcmove.cpp.

3878 {
3879  map_stack stack = get_map().i_at( where );
3880  return npc_pickup_from_stack( *this, stack );
3881 }
std::list< item > npc_pickup_from_stack(npc &who, T &items)
Definition: npcmove.cpp:3771

References get_map(), map::i_at(), and npc_pickup_from_stack().

Referenced by pick_up_item().

◆ pick_up_item_vehicle()

std::list< item > npc::pick_up_item_vehicle ( vehicle veh,
int  part_index 
)

Definition at line 3883 of file npcmove.cpp.

3884 {
3885  vehicle_stack stack = veh.get_items( veh.part( part_index ) );
3886  return npc_pickup_from_stack( *this, stack );
3887 }
vehicle_stack get_items(const vehicle_part &vp) const
Definition: vehicle.cpp:5922
vehicle_part & part(int part_num)
Definition: vehicle.cpp:8098

References vehicle::get_items(), npc_pickup_from_stack(), and vehicle::part().

Referenced by pick_up_item().

◆ place_on_map()

void npc::place_on_map ( )

Places the NPC on the map.

This update its pos values to fit the current offset of map (g->levx, g->levy). If the square on the map where the NPC would go is not empty a spiral search for an empty square around it is performed.

Definition at line 1015 of file npc.cpp.

1016 {
1017  if( g->is_empty( pos() ) || is_mounted() ) {
1018  return;
1019  }
1020 
1021  for( const tripoint &p : closest_points_first( pos(), SEEX + 1 ) ) {
1022  if( g->is_empty( p ) ) {
1023  setpos( p );
1024  return;
1025  }
1026  }
1027 
1028  debugmsg( "Failed to place NPC in a valid location near (%d,%d,%d)", posx(), posy(), posz() );
1029 }

References closest_points_first(), debugmsg, g, Character::is_mounted(), Creature::pos(), Creature::posx(), Creature::posy(), Creature::posz(), SEEX, and Creature::setpos().

◆ prepare_for_combat()

void npc::prepare_for_combat ( )

Definition at line 2369 of file npcmove.cpp.

2370 {
2373 }
void activate_combat_items()
Definition: npcmove.cpp:2344
void activate_combat_cbms()
Definition: npcmove.cpp:2209

References activate_combat_cbms(), and activate_combat_items().

Referenced by method_of_attack().

◆ pretend_fire()

void npc::pretend_fire ( npc source,
int  shots,
item gun 
)

Definition at line 835 of file ranged.cpp.

836 {
837  int curshot = 0;
838  if( one_in( 50 ) ) {
839  add_msg_if_player_sees( *source, m_info, _( "%s shoots something." ), source->disp_name() );
840  }
841  while( curshot != shots ) {
842  const int required = gun.ammo_required();
843  if( gun.ammo_consume( required, pos(), this ) != required ) {
844  debugmsg( "Unexpected shortage of ammo whilst firing %s", gun.tname().c_str() );
845  break;
846  }
847 
848  item *weapon = &gun;
849  const item::sound_data data = weapon->gun_noise( shots > 1 );
850 
851  add_msg_if_player_sees( *source, m_warning, _( "You hear %s." ), data.sound );
852  curshot++;
853  mod_moves( -get_speed() );
854  }
855 }
sound_data gun_noise(bool burst=false) const
Returns the sound of the gun being fired.
Definition: ranged.cpp:2185
@ m_warning
Definition: enums.h:351
std::string sound
Sound description, can be used with sounds::sound, it is already translated.
Definition: item.h:2624

References _, add_msg_if_player_sees(), debugmsg, Character::disp_name(), Character::get_speed(), gun, item::gun_noise(), m_info, m_warning, Creature::mod_moves(), one_in(), Creature::pos(), item::sound_data::sound, and Character::weapon.

Referenced by execute_action(), and npc_attack_gun::use().

◆ pretend_heal()

void npc::pretend_heal ( Character patient,
item  used 
)

Definition at line 4365 of file npcmove.cpp.

4366 {
4367  // you can tell that it's not real by looking at your HP though
4368  add_msg_if_player_sees( *this, _( "%1$s heals %2$s." ), disp_name(),
4369  patient.disp_name() );
4370  consume_charges( used, 1 ); // empty hallucination's inventory to avoid spammming
4371  mod_moves( -get_speed() ); // consumes moves to avoid infinite loop
4372 }

References _, add_msg_if_player_sees(), Character::consume_charges(), Character::disp_name(), Character::get_speed(), and Creature::mod_moves().

Referenced by heal_player().

◆ prevent_death()

void npc::prevent_death ( )
overridevirtual

Reimplemented from Character.

Definition at line 2910 of file npc.cpp.

2911 {
2912  marked_for_death = false;
2913  prevent_death_reminder = true;
2915 }
virtual void prevent_death()
Definition: character.cpp:3586

References marked_for_death, Character::prevent_death(), and prevent_death_reminder.

◆ print_info()

int npc::print_info ( const catacurses::window w,
int  vStart,
int  vLines,
int  column 
) const
overridevirtual

Write information about this creature.

Parameters
wthe window to print the text into.
vStartvertical start to print, that means the first line to print.
vLinesnumber of lines to print at most (printing less is fine).
columnhorizontal start to print (column), horizontal end is one character before the right border of the window (to keep the border).
Returns
The line just behind the last printed line, that means multiple calls to this can be stacked, the return value is acceptable as vStart for the next call without creating empty lines or overwriting lines.

Implements Creature.

Definition at line 2572 of file npc.cpp.

2573 {
2574  const int last_line = line + vLines;
2575  const int iWidth = getmaxx( w ) - 1 - column;
2576  // First line of w is the border; the next 4 are terrain info, and after that
2577  // is a blank line. w is 13 characters tall, and we can't use the last one
2578  // because it's a border as well; so we have lines 6 through 11.
2579  // w is also 53 characters wide - 2 characters for border = 51 characters for us
2580 
2581  // Print health bar and NPC name on the first line.
2582  std::pair<std::string, nc_color> bar = get_hp_bar( hp_percentage(), 100 );
2583  mvwprintz( w, point( column, line ), bar.second, bar.first );
2584  const int bar_max_width = 5;
2585  const int bar_width = utf8_width( bar.first );
2586  for( int i = 0; i < bar_max_width - bar_width; ++i ) {
2587  mvwprintz( w, point( column + 4 - i, line ), c_white, "." );
2588  }
2589  line += fold_and_print( w, point( column + bar_max_width + 1, line ),
2590  iWidth - bar_max_width - 1, basic_symbol_color(), get_name() );
2591 
2592  Character &player_character = get_player_character();
2593  // Hostility and current attitude indicator on the second line.
2594  Attitude att = attitude_to( player_character );
2595  const std::pair<translation, nc_color> res = Creature::get_attitude_ui_data( att );
2596  mvwprintz( w, point( column, line++ ), res.second, res.first.translated() );
2597  wprintz( w, c_light_gray, ";" );
2598  wprintz( w, symbol_color(), " %s", npc_attitude_name( get_attitude() ) );
2599 
2600  // Awareness indicator on the third line.
2601  std::string senses_str = sees( player_character ) ? _( "Aware of your presence" ) :
2602  _( "Unaware of you" );
2603  line += fold_and_print( w, point( column, line ), iWidth,
2604  sees( player_character ) ? c_yellow : c_green,
2605  senses_str );
2606 
2607  // Print what item the NPC is holding if any on the fourth line.
2608  if( is_armed() ) {
2609  line += fold_and_print( w, point( column, line ), iWidth, c_red,
2610  std::string( "<color_light_gray>" ) + _( "Wielding: " ) + std::string( "</color>" ) +
2611  get_wielded_item()->tname() );
2612  }
2613 
2614  // Worn gear list on following lines.
2615  const std::list<item> visible_worn_items = get_visible_worn_items();
2616  const std::string worn_str = enumerate_as_string( visible_worn_items.begin(),
2617  visible_worn_items.end(), []( const item & it ) {
2618  return it.tname();
2619  } );
2620  if( !worn_str.empty() ) {
2621  std::vector<std::string> worn_lines = foldstring( _( "Wearing: " ) + worn_str, iWidth );
2622  int worn_numlines = worn_lines.size();
2623  for( int i = 0; i < worn_numlines && line < last_line; i++ ) {
2624  if( line + 1 == last_line ) {
2625  worn_lines[i].append( "…" );
2626  }
2627  trim_and_print( w, point( column, line++ ), iWidth, c_light_gray, worn_lines[i] );
2628  }
2629  }
2630 
2631  if( line == last_line ) {
2632  return line;
2633  }
2634 
2635  int visibility_cap = player_character.get_mutation_visibility_cap( this );
2636  const std::string trait_str = visible_mutations( visibility_cap );
2637  if( !trait_str.empty() ) {
2638  std::vector<std::string> trait_lines = foldstring( _( "Traits: " ) + trait_str, iWidth );
2639  int trait_numlines = trait_lines.size();
2640  for( int i = 0; i < trait_numlines && line < last_line; i++ ) {
2641  if( line + 1 == last_line ) {
2642  trait_lines[i].append( "…" );
2643  }
2644  trim_and_print( w, point( column, line++ ), iWidth, c_light_gray, trait_lines[i] );
2645  }
2646  }
2647 
2648  return line;
2649 }
int get_mutation_visibility_cap(const Character *observed) const
Returns the mutation visibility threshold for the observer ( *this )
std::list< item > get_visible_worn_items() const
Returns all worn items visible to an outside observer.
std::string visible_mutations(int visibility_cap) const
Returns an enumeration of visible mutations with colors.
Definition: mutation.cpp:2431
nc_color symbol_color() const override
Creature symbol background color.
Definition: character.cpp:5745
static const std::pair< translation, nc_color > & get_attitude_ui_data(Attitude att)
Creature Attitude as String and color.
Definition: creature.cpp:3088
nc_color basic_symbol_color() const override
Creature symbol color.
Definition: npc.cpp:2556
std::string npc_attitude_name(npc_attitude att)
Definition: npc.cpp:2959
std::pair< std::string, nc_color > get_hp_bar(const int cur_hp, const int max_hp, const bool is_mon)
Definition: output.cpp:2657
void trim_and_print(const catacurses::window &w, const point &begin, const int width, const nc_color &base_color, const std::string &text, const report_color_error color_error)
Prints a single line of text.
Definition: output.cpp:268
std::vector< std::string > foldstring(const std::string &str, int width, const char split)
Split the input text into separate lines and wrap long lines.
Definition: output.cpp:123
void wprintz(const catacurses::window &w, const nc_color &FG, const std::string &text)
Definition: output.cpp:3298
std::string enumerate_as_string(const Container &values, enumeration_conjunction conj=enumeration_conjunction::and_)
Definition: output.h:647

References _, attitude_to(), basic_symbol_color(), c_green, c_light_gray, c_red, c_white, c_yellow, enumerate_as_string(), fold_and_print(), foldstring(), get_attitude(), Creature::get_attitude_ui_data(), get_hp_bar(), Character::get_mutation_visibility_cap(), Character::get_name(), get_player_character(), Character::get_visible_worn_items(), Character::get_wielded_item(), catacurses::getmaxx(), Character::hp_percentage(), Character::is_armed(), line, mvwprintz(), npc_attitude_name(), point, Character::sees(), Character::symbol_color(), trim_and_print(), utf8_width(), Character::visible_mutations(), and wprintz().

◆ process_turn()

void npc::process_turn ( )
overridevirtual

Handles end-of-turn processing.

Reimplemented from Character.

Definition at line 3181 of file npc.cpp.

3182 {
3184 
3185  // NPCs shouldn't be using stamina, but if they have, set it back to max
3186  // If the stamina is higher than the max (Languorous), set it back to max
3187  if( calendar::once_every( 1_minutes ) && get_stamina() != get_stamina_max() ) {
3189  }
3190 
3191  if( is_player_ally() && calendar::once_every( 1_hours ) &&
3192  get_hunger() < 200 && get_thirst() < 100 && op_of_u.trust < 5 ) {
3193  // Friends who are well fed will like you more
3194  // 24 checks per day, best case chance at trust 0 is 1 in 48 for +1 trust per 2 days
3195  float trust_chance = 5 - op_of_u.trust;
3196  // Penalize for bad impression
3197  // TODO: Penalize for traits and actions (especially murder, unless NPC is psycho)
3198  int op_penalty = std::max( 0, op_of_u.anger ) +
3199  std::max( 0, -op_of_u.value ) +
3200  std::max( 0, op_of_u.fear );
3201  // Being barely hungry and thirsty, not in pain and not wounded means good care
3202  int state_penalty = get_hunger() + get_thirst() + ( 100 - hp_percentage() ) + get_pain();
3203  if( x_in_y( trust_chance, 240 + 10 * op_penalty + state_penalty ) ) {
3204  op_of_u.trust++;
3205  }
3206 
3207  // TODO: Similar checks for fear and anger
3208  }
3209 
3210  // TODO: Add decreasing trust/value/etc. here when player doesn't provide food
3211  // TODO: Make NPCs leave the player if there's a path out of map and player is sleeping/unseen/etc.
3212 }
bool x_in_y(const time_duration &a, const time_duration &b)
Definition: calendar.cpp:784
int get_stamina() const
Definition: character.cpp:6806
void process_turn() override
Handles end-of-turn processing.
Definition: character.cpp:2309
void set_stamina(int new_stamina)
Definition: character.cpp:6836
int get_stamina_max() const
Definition: character.cpp:6815

References npc_opinion::anger, npc_opinion::fear, Character::get_hunger(), Creature::get_pain(), Character::get_stamina(), Character::get_stamina_max(), get_thirst(), Character::hp_percentage(), is_player_ally(), max(), calendar::once_every(), op_of_u, Character::process_turn(), Character::set_stamina(), npc_opinion::trust, npc_opinion::value, and x_in_y().

◆ query_yn()

bool npc::query_yn ( const std::string &  mes) const
overridevirtual

Implements Character.

Definition at line 3161 of file npc.cpp.

3162 {
3163  // NPCs don't like queries - most of them are in the form of "Do you want to get hurt?".
3164  return false;
3165 }

◆ randomize()

void npc::randomize ( const npc_class_id type = npc_class_id::NULL_ID(),
const npc_template_id tem_id = npc_template_id::NULL_ID() 
)

Definition at line 551 of file npc.cpp.

552 {
553  if( !getID().is_valid() ) {
554  setID( g->assign_npc_id() );
555  }
556 
558  inv->clear();
559  personality.aggression = rng( -10, 10 );
560  personality.bravery = rng( -3, 10 );
561  personality.collector = rng( -1, 10 );
562  // Normal distribution. Mean = 0, stddev = 3, clamp at -10 and 10. Rounded to return integer value.
563  personality.altruism = std::round( std::max( -10.0, std::min( normal_roll( 0, 3 ), 10.0 ) ) );
564  moves = 100;
566  male = one_in( 2 );
567  pick_name();
569  set_base_age( rng( 18, 55 ) );
570  str_max = dice( 4, 3 );
571  dex_max = dice( 4, 3 );
572  int_max = dice( 4, 3 );
573  per_max = dice( 4, 3 );
574 
575  if( tem_id.is_valid() ) {
576  const npc_template &tem = tem_id.obj();
577  if( tem.personality.has_value() ) {
578  personality.aggression = tem.personality->aggression;
579  personality.bravery = tem.personality->bravery;
580  personality.collector = tem.personality->collector;
581  personality.altruism = tem.personality->altruism;
582  }
583  if( tem.str.has_value() ) {
584  str_max = tem.str.value();
585  }
586  if( tem.dex.has_value() ) {
587  dex_max = tem.dex.value();
588  }
589  if( tem.intl.has_value() ) {
590  int_max = tem.intl.value();
591  }
592  if( tem.per.has_value() ) {
593  per_max = tem.per.value();
594  }
595  if( tem.height.has_value() ) {
596  set_base_height( tem.height.value() );
597  }
598  if( tem.age.has_value() ) {
599  set_base_age( tem.age.value() );
600  }
601  }
602 
603  if( !type.is_valid() ) {
604  debugmsg( "Invalid NPC class %s", type.c_str() );
606  } else if( type.is_null() ) {
608  } else {
609  myclass = type;
610  }
611 
612  const npc_class &the_class = myclass.obj();
613  str_max += the_class.roll_strength();
614  dex_max += the_class.roll_dexterity();
615  int_max += the_class.roll_intelligence();
616  per_max += the_class.roll_perception();
617 
618  personality.aggression += the_class.roll_aggression();
619  personality.bravery += the_class.roll_bravery();
620  personality.collector += the_class.roll_collector();
621  personality.altruism += the_class.roll_altruism();
622 
629 
630  for( Skill &skill : Skill::skills ) {
631  int level = myclass->roll_skill( skill.ident() );
632 
633  set_skill_level( skill.ident(), level );
634  }
635 
636  //A universal barter boost to keep NPCs competitive with players
637  //The int boost from trade wasn't active... now that it is, most
638  //players will vastly outclass npcs in trade without a little help.
639  mod_skill_level( skill_speech, rng( 2, 4 ) );
640 
641  set_body();
642  recalc_hp();
643  int days_since_cata = to_days<int>( calendar::turn - calendar::start_of_cataclysm );
644  double time_influence = days_since_cata >= 180 ? 3.0 : 6.0 - 3.0 * days_since_cata / 180.0;
645  double weight_percent = std::clamp<double>( chi_squared_roll( time_influence ) / 5.0,
646  0.2, 5.0 );
647  set_stored_kcal( weight_percent * get_healthy_kcal() );
649  starting_clothes( *this, myclass, male );
650  starting_inv( *this, myclass );
651  has_new_items = true;
652  clear_mutations();
653 
654  // Add fixed traits
655  for( const trait_and_var &cur : trait_group::traits_from( myclass->traits ) ) {
656  const trait_id &tid = cur.trait;
657  const std::string &var = cur.variant;
658  set_mutation( tid, tid->variant( var ) );
659  }
660 
661  // Add personality traits
663 
664  // Run mutation rounds
665  for( const auto &mr : type->mutation_rounds ) {
666  int rounds = mr.second.roll();
667  for( int i = 0; i < rounds; ++i ) {
668  mutate_category( mr.first );
669  }
670  }
671  // Add bionics
672  for( const auto &bl : type->bionic_list ) {
673  int chance = bl.second;
674  if( rng( 0, 100 ) <= chance ) {
675  add_bionic( bl.first );
676  }
677  }
678  // Add proficiencies
679  for( const proficiency_id &prof : type->_starting_proficiencies ) {
681  }
682  // Add martial arts
684  // Add spells for magiclysm mod
685  for( std::pair<spell_id, int> spell_pair : type->_starting_spells ) {
686  this->magic->learn_spell( spell_pair.first, *this, true );
687  spell &sp = this->magic->get_spell( spell_pair.first );
688  while( sp.get_level() < spell_pair.second && !sp.is_max_level( *this ) ) {
689  sp.gain_level( *this );
690  }
691  }
692 
693  // Add eocs
695 }
void mutate_category(const mutation_category_id &mut_cat, bool use_vitamins, bool true_random=false)
Picks a random valid mutation in a category and mutate_towards() it.
Definition: mutation.cpp:1273
void set_base_age(int age)
Definition: character.cpp:6435
void clear_mutations()
Empties the trait and mutations lists.
void set_stored_kcal(int kcal)
Setters for need values exclusive to characters.
Definition: character.cpp:4450
void add_proficiency(const proficiency_id &prof, bool ignore_requirements=false)
bionic_uid add_bionic(const bionic_id &b, bionic_uid parent_uid=0, bool suppress_debug=false)
Adds a bionic to my_bionics[].
Definition: bionics.cpp:2722
const profession * prof
Definition: character.h:588
void set_skill_level(const skill_id &ident, int level)
Definition: character.cpp:3467
void mod_skill_level(const skill_id &ident, int delta)
Definition: character.cpp:3472
void recalc_hp()
Recalculates HP after a change to max strength or enchantment.
Definition: character.cpp:2464
void pick_name(bool bUseDefault=false)
Returns a random name from NAMES_*.
void set_base_height(int height)
Definition: character.cpp:6494
void randomize_height()
Definition: character.cpp:666
void set_body()
Definition: creature.cpp:2172
static std::vector< Skill > skills
Definition: skill.h:52
int roll_aggression() const
Definition: npc_class.cpp:477
int roll_perception() const
Definition: npc_class.cpp:472
int roll_collector() const
Definition: npc_class.cpp:487
int roll_strength() const
Definition: npc_class.cpp:457
int roll_skill(const skill_id &) const
Definition: npc_class.cpp:497
int roll_dexterity() const
Definition: npc_class.cpp:462
trait_group::Trait_group_tag traits
Definition: npc_class.h:113
int roll_altruism() const
Definition: npc_class.cpp:492
int roll_intelligence() const
Definition: npc_class.cpp:467
int roll_bravery() const
Definition: npc_class.cpp:482
static const npc_class_id & random_common()
Definition: npc_class.cpp:391
std::optional< int > per
Definition: npc.h:1511
std::optional< int > height
Definition: npc.h:1507
std::optional< int > dex
Definition: npc.h:1509
std::optional< int > intl
Definition: npc.h:1510
std::optional< npc_personality > personality
Definition: npc.h:1512
std::optional< int > str
Definition: npc.h:1508
std::optional< int > age
Definition: npc.h:1506
void starting_weapon(const npc_class_id &type)
Definition: npc.cpp:1066
void learn_ma_styles_from_traits()
Definition: npc.cpp:723
Definition: magic.h:422
int get_level() const
Definition: magic.cpp:1570
void gain_level(const Character &guy)
Definition: magic.cpp:1005
bool is_max_level(const Creature &caster) const
Definition: magic.cpp:1026
time_point start_of_cataclysm
Definition: calendar.cpp:36
void load_new_character(Character &you)
Sets up the initial queue for a new character.
Trait_list traits_from(const Trait_group_tag &gid)
Returns a randomized list of traits from the given trait group.
Definition: trait_group.cpp:21
static void starting_inv(npc &who, const npc_class_id &type)
Definition: npc.cpp:866
static const skill_id skill_speech("speech")
static void starting_clothes(npc &who, const npc_class_id &type, bool male)
Definition: npc.cpp:825
constexpr int8_t NPC_PERSONALITY_MAX
Definition: npc.h:61
constexpr int8_t NPC_PERSONALITY_MIN
Definition: npc.h:60
double normal_roll(double mean, double stddev)
Definition: rng.cpp:78
double chi_squared_roll(double trial_num)
Definition: rng.cpp:91
const mutation_variant * variant(const std::string &id) const
Returns a pointer to the mutation variant with corresponding id, or nullptr if none exists.

References Character::add_bionic(), Character::add_proficiency(), npc_template::age, npc_personality::aggression, npc_personality::altruism, npc_personality::bravery, chi_squared_roll(), clamp(), Character::clear_mutations(), npc_personality::collector, debugmsg, npc_template::dex, Character::dex_max, dice(), g, spell::gain_level(), generate_personality_traits(), Character::get_healthy_kcal(), spell::get_level(), Character::getID(), has_new_items, npc_template::height, Character::int_max, npc_template::intl, Character::inv, spell::is_max_level(), string_id< T >::is_valid(), item, learn_ma_styles_from_traits(), effect_on_conditions::load_new_character(), Character::magic, Character::male, max(), min(), Character::mod_skill_level(), Creature::moves, Character::mutate_category(), myclass, normal_roll(), NPC_MISSION_NULL, NPC_PERSONALITY_MAX, NPC_PERSONALITY_MIN, string_id< npc_class >::NULL_ID(), string_id< T >::obj(), one_in(), npc_template::per, Character::per_max, personality, npc_template::personality, Character::pick_name(), Character::prof, npc_class::random_common(), Character::randomize_height(), Character::recalc_hp(), rng(), npc_class::roll_aggression(), npc_class::roll_altruism(), npc_class::roll_bravery(), npc_class::roll_collector(), npc_class::roll_dexterity(), npc_class::roll_intelligence(), npc_class::roll_perception(), npc_class::roll_skill(), npc_class::roll_strength(), round(), Character::set_base_age(), Character::set_base_height(), Creature::set_body(), Character::set_mutation(), Character::set_skill_level(), Character::set_stored_kcal(), Character::set_wielded_item(), Character::setID(), skill_speech, Skill::skills, calendar::start_of_cataclysm, starting_clothes(), starting_inv(), starting_weapon(), npc_template::str, Character::str_max, npc_class::traits, trait_group::traits_from(), calendar::turn, calendar::turn_zero, type, and mutation_branch::variant().

Referenced by debug_menu::character_edit_menu(), load_npc_template(), and randomize_from_faction().

◆ randomize_from_faction()

void npc::randomize_from_faction ( faction fac)

Definition at line 740 of file npc.cpp.

741 {
742  // Personality = aggression, bravery, altruism, collector
743  set_fac( fac->id );
745 }

References faction_template::id, string_id< npc_class >::NULL_ID(), randomize(), and set_fac().

◆ reach_omt_destination()

void npc::reach_omt_destination ( )

Definition at line 4795 of file npcmove.cpp.

4796 {
4797  if( !omt_path.empty() ) {
4798  omt_path.clear();
4799  }
4800  map &here = get_map();
4801  if( is_travelling() ) {
4802  guard_pos = get_location();
4803  goal = no_goal_point;
4804  if( is_player_ally() ) {
4805  Character &player_character = get_player_character();
4806  talk_function::assign_guard( *this );
4807  if( rl_dist( player_character.pos(), pos() ) > SEEX * 2 ) {
4808  if( player_character.cache_has_item_with_flag( flag_TWO_WAY_RADIO, true ) &&
4810  add_msg_if_player_sees( pos(), m_info, _( "From your two-way radio you hear %s reporting in, "
4811  "'I've arrived, boss!'" ), disp_name() );
4812  }
4813  }
4814  } else {
4815  // for now - they just travel to a nearby place they want as a base
4816  // and chill there indefinitely, the plan is to add systems for them to build
4817  // up their base, then go out on looting missions,
4818  // then return to base afterwards.
4820  if( !needs.empty() && needs[0] == need_safety ) {
4821  // we found our base.
4823  }
4824  }
4825  return;
4826  }
4827  // Guarding NPCs want a specific point, not just an overmap tile
4828  // Rest stops having a goal after reaching it
4829  if( !( is_guarding() || is_patrolling() ) ) {
4830  goal = no_goal_point;
4831  return;
4832  }
4833  // If we are guarding, remember our position in case we get forcibly moved
4835  if( guard_pos && *guard_pos == get_location() ) {
4836  // This is the specific point
4837  return;
4838  }
4839 
4840  if( path.size() > 1 ) {
4841  // No point recalculating the path to get home
4842  move_to_next();
4843  } else if( guard_pos ) {
4844  update_path( here.getlocal( *guard_pos ) );
4845  move_to_next();
4846  } else {
4847  guard_pos = get_location();
4848  }
4849 }
bool is_travelling() const
Definition: npc.cpp:2381
const flag_id flag_TWO_WAY_RADIO("TWO_WAY_RADIO")

References _, add_msg_if_player_sees(), talk_function::assign_guard(), base_location, Character::cache_has_item_with_flag(), Character::disp_name(), flag_TWO_WAY_RADIO, Creature::get_location(), get_map(), get_player_character(), map::getlocal(), Creature::global_omt_location(), goal, guard_pos, is_guarding(), is_patrolling(), is_player_ally(), is_travelling(), m_info, move_to_next(), need_safety, needs, no_goal_point, NPC_MISSION_GUARD, Character::omt_path, path, Creature::pos(), rl_dist(), SEEX, set_mission(), and update_path().

Referenced by go_to_omt_destination(), and travel_overmap().

◆ reboot()

void npc::reboot ( )

Definition at line 2751 of file npc.cpp.

2752 {
2753  //The NPC got into an infinite loop, in game.cpp -monmove() - a debugmsg just popped up
2754  // informing player of this.
2755  // put them to sleep and reboot their brain.
2756  // they can be woken up by the player, and if their brain is fixed, great,
2757  // if not, they will faint again, and the NPC can be kept asleep until the bug is fixed.
2758  cancel_activity();
2759  path.clear();
2760  last_player_seen_pos = std::nullopt;
2761  last_seen_player_turn = 999;
2763  guard_pos = std::nullopt;
2764  goal = no_goal_point;
2765  fetching_item = false;
2766  has_new_items = true;
2767  worst_item_value = 0;
2769  patience = 0;
2770  ai_cache.danger = 0;
2771  ai_cache.total_danger = 0;
2773  ai_cache.target.reset();
2774  ai_cache.ally.reset();
2776  ai_cache.sound_alerts.clear();
2778  ai_cache.stuck = 0;
2779  ai_cache.guard_pos = std::nullopt;
2781  ai_cache.friends.clear();
2783  ai_cache.threat_map.clear();
2787  add_effect( effect_npc_suspend, 24_hours, true, 1 );
2788 }
void cancel_activity()
Definition: character.cpp:8983
void clear()
Definition: lru_cache.h:82
static const efftype_id effect_npc_suspend("npc_suspend")
constexpr tripoint tripoint_zero
Definition: point.h:250

References Character::activity, Creature::add_effect(), ai_cache, npc_short_term_cache::ally, npc_short_term_cache::can_heal, Character::cancel_activity(), lru_cache< Key, Value >::clear(), healing_options::clear_all(), Character::clear_destination(), npc_short_term_cache::danger, npc_short_term_cache::danger_assessment, npc_short_term_cache::dangerous_explosives, effect_npc_suspend, fetching_item, npc_short_term_cache::friends, goal, npc_short_term_cache::guard_pos, guard_pos, has_new_items, last_player_seen_pos, last_seen_player_turn, npc_short_term_cache::my_weapon_value, no_goal_point, NPC_MISSION_NULL, path, patience, npc_short_term_cache::s_abs_pos, npc_short_term_cache::searched_tiles, npc_short_term_cache::sound_alerts, npc_short_term_cache::stuck, npc_short_term_cache::target, npc_short_term_cache::threat_map, npc_short_term_cache::total_danger, tripoint_min, tripoint_zero, wanted_item_pos, and worst_item_value.

◆ recharge_cbm()

bool npc::recharge_cbm ( )

Definition at line 2299 of file npcmove.cpp.

2300 {
2301  // non-allied NPCs don't consume resources to recharge
2302  if( !is_player_ally() ) {
2304  return true;
2305  }
2306 
2307  for( bionic_id &bid : get_fueled_bionics() ) {
2308  if( has_active_bionic( bid ) ) {
2309  continue;
2310  }
2311 
2312  if( !get_bionic_fuels( bid ).empty() ) {
2313  use_bionic_by_id( bid );
2314  return true;
2315  }
2316  }
2317 
2318  return false;
2319 }
std::vector< bionic_id > get_fueled_bionics() const
Return bionic_id of fueled bionics.
Definition: bionics.cpp:3288
std::vector< item * > get_bionic_fuels(const bionic_id &bio)
Return list of available fuel sources that are not empty for this bionic.
Definition: bionics.cpp:3309
bool has_active_bionic(const bionic_id &b) const
Returns true if the player has the entered bionic id and it is powered on.
Definition: bionics.cpp:2658

References Character::get_bionic_fuels(), Character::get_fueled_bionics(), Character::get_max_power_level(), Character::has_active_bionic(), is_player_ally(), Character::mod_power_level(), and use_bionic_by_id().

Referenced by address_needs().

◆ regen_ai_cache()

void npc::regen_ai_cache ( )

Definition at line 1215 of file npcmove.cpp.

1216 {
1217  map &here = get_map();
1218  auto i = std::begin( ai_cache.sound_alerts );
1219  creature_tracker &creatures = get_creature_tracker();
1221  if( !ai_cache.guard_pos ) {
1223  }
1224  }
1225  while( i != std::end( ai_cache.sound_alerts ) ) {
1226  if( sees( here.getlocal( i->abs_pos ) ) ) {
1227  // if they were responding to a call for guards because of thievery
1228  npc *const sound_source = creatures.creature_at<npc>( here.getlocal( i->abs_pos ) );
1229  if( sound_source ) {
1230  if( my_fac == sound_source->my_fac && sound_source->known_stolen_item ) {
1231  sound_source->known_stolen_item = nullptr;
1233  }
1234  }
1235  i = ai_cache.sound_alerts.erase( i );
1236  if( ai_cache.sound_alerts.size() == 1 ) {
1237  path.clear();
1238  }
1239  } else {
1240  ++i;
1241  }
1242  }
1243  float old_assessment = ai_cache.danger_assessment;
1244  ai_cache.friends.clear();
1245  ai_cache.hostile_guys.clear();
1246  ai_cache.neutral_guys.clear();
1250  ai_cache.danger = 0.0f;
1251  ai_cache.total_danger = 0.0f;
1256 
1257  mem_combat.assess_enemy = 0.0f;
1258  mem_combat.assess_ally = 0.0f;
1259  mem_combat.swarm_count = 0;
1260  if( mem_combat.reposition_countdown > 0 ) {
1262  }
1263 
1266  // if NPC no longer has the run away effect and isn't fleeing in panic,
1267  // they can stop moving away.
1268  mem_combat.repositioning = false;
1270  path.clear();
1271  }
1272 
1273  assess_danger();
1274  if( old_assessment > NPC_DANGER_VERY_LOW && ai_cache.danger_assessment <= 0 ) {
1275  warn_about( "relax", 30_minutes );
1276  } else if( old_assessment <= 0.0f && ai_cache.danger_assessment > NPC_DANGER_VERY_LOW ) {
1277  warn_about( "general_danger" );
1278  }
1279  // Non-allied NPCs with a completed mission should move to the player
1280  if( !is_player_ally() && !is_stationary( true ) ) {
1281  Character &player_character = get_player_character();
1282  for( ::mission *miss : chatbin.missions_assigned ) {
1283  if( miss->is_complete( getID() ) ) {
1284  // unless the player found an item and already told the NPC he wanted to keep it
1285  const mission_goal &mgoal = miss->get_type().goal;
1286  if( ( mgoal == MGOAL_FIND_ITEM || mgoal == MGOAL_FIND_ANY_ITEM ||
1287  mgoal == MGOAL_FIND_ITEM_GROUP ) &&
1289  continue;
1290  }
1291  if( global_omt_location() != player_character.global_omt_location() ) {
1292  goal = player_character.global_omt_location();
1293  }
1295  break;
1296  }
1297  }
1298  }
1299 }
bool is_complete(const character_id &npc_id) const
Checks if the player has completed the matching mission and returns true if they have.
Definition: mission.cpp:467
const mission_type & get_type() const
Definition: mission.cpp:714
std::vector< sphere > find_dangerous_explosives() const
Definition: npcmove.cpp:434
void assess_danger()
Definition: npcmove.cpp:707
item * known_stolen_item
Definition: npc.h:1382
mission_goal
Definition: mission.h:60
@ MGOAL_FIND_ITEM_GROUP
Definition: mission.h:66
@ MGOAL_FIND_ITEM
Definition: mission.h:64
@ MGOAL_FIND_ANY_ITEM
Definition: mission.h:65
@ end
Definition: input.h:95
static const efftype_id effect_npc_player_still_looking("npc_player_still_looking")
static const trait_id trait_RETURN_TO_START_POS("RETURN_TO_START_POS")
mission_goal goal
Definition: mission.h:190

References ai_cache, npc_short_term_cache::ally, npc_combat_memory_cache::assess_ally, assess_danger(), npc_combat_memory_cache::assess_enemy, npc_short_term_cache::can_heal, chatbin, healing_options::clear_all(), creature_tracker::creature_at(), npc_short_term_cache::danger, npc_short_term_cache::danger_assessment, npc_short_term_cache::dangerous_explosives, effect_npc_fire_bad, effect_npc_player_still_looking, effect_npc_run_away, keycode::end, find_dangerous_explosives(), npc_combat_memory_cache::formation_distance, npc_short_term_cache::friends, get_creature_tracker(), Creature::get_location(), get_map(), get_player_character(), mission::get_type(), Character::get_wielded_item(), Character::getID(), map::getlocal(), Creature::global_omt_location(), mission_type::goal, goal, npc_short_term_cache::guard_pos, Creature::has_effect(), Character::has_trait(), npc_short_term_cache::hostile_guys, mission::is_complete(), is_player_ally(), is_stationary(), known_stolen_item, mem_combat, MGOAL_FIND_ANY_ITEM, MGOAL_FIND_ITEM, MGOAL_FIND_ITEM_GROUP, dialogue_chatbin::missions_assigned, Character::my_fac, npc_short_term_cache::my_weapon_value, npc_short_term_cache::neutral_guys, NPC_DANGER_VERY_LOW, NPCATT_RECOVER_GOODS, NPCATT_TALK, null_item_reference(), path, npc_combat_memory_cache::reposition_countdown, npc_combat_memory_cache::repositioning, Character::sees(), set_attitude(), npc_short_term_cache::sound_alerts, npc_combat_memory_cache::swarm_count, npc_short_term_cache::target, npc_short_term_cache::total_danger, trait_RETURN_TO_START_POS, warn_about(), Character::weapon, and Character::weapon_value().

Referenced by move().

◆ reset_companion_mission()

void npc::reset_companion_mission ( )

Unset a companion mission. Precondition: !has_companion_mission()

Definition at line 3466 of file npc.cpp.

3467 {
3468  comp_mission.position = tripoint_abs_omt( -999, -999, -999 );
3470  comp_mission.role_id.clear();
3471  if( comp_mission.destination ) {
3472  comp_mission.destination = std::nullopt;
3473  }
3474 }
void reset_miss_id(mission_id &miss_id)

References comp_mission, npc_companion_mission::destination, npc_companion_mission::miss_id, npc_companion_mission::position, reset_miss_id(), and npc_companion_mission::role_id.

Referenced by talk_function::companion_return(), basecamp::finish_return(), import_and_clean(), and talk_function::stop_guard().

◆ revert_after_activity()

void npc::revert_after_activity ( )

◆ saw_player_recently()

bool npc::saw_player_recently ( ) const

Definition at line 4784 of file npcmove.cpp.

4785 {
4788 }
bool inbounds(const tripoint &p) const
Definition: map.cpp:9057

References get_map(), map::inbounds(), last_player_seen_pos, and last_seen_player_turn.

Referenced by execute_action().

◆ say() [1/2]

template<typename ... Args>
void npc::say ( const char *const  line,
Args &&...  args 
) const
inline

◆ say() [2/2]

void npc::say ( const std::string &  line,
sounds::sound_t  spriority = sounds::sound_t::speech 
) const

Definition at line 1729 of file npc.cpp.

1730 {
1731  std::string formatted_line = line;
1732  Character &player_character = get_player_character();
1733  parse_tags( formatted_line, player_character, *this );
1734  if( has_trait( trait_MUTE ) ) {
1735  return;
1736  }
1737 
1738  if( player_character.is_deaf() && !player_character.is_blind() ) {
1739  add_msg_if_player_sees( *this, m_warning, _( "%1$s says something but you can't hear it!" ),
1740  get_name() );
1741  }
1742  if( player_character.is_mute() ) {
1743  add_msg_if_player_sees( *this, m_warning, _( "%1$s says something but you can't reply to it!" ),
1744  get_name() );
1745  }
1746  // Hallucinations don't make noise when they speak
1747  if( is_hallucination() ) {
1748  add_msg( _( "%1$s saying \"%2$s\"" ), get_name(), formatted_line );
1749  return;
1750  }
1751 
1752  std::string sound = string_format( _( "%1$s saying \"%2$s\"" ), get_name(), formatted_line );
1753 
1754  // Sound happens even if we can't hear it
1755  if( spriority == sounds::sound_t::order || spriority == sounds::sound_t::alert ) {
1756  sounds::sound( pos(), get_shout_volume(), spriority, sound, false, "speech",
1757  male ? "NPC_m" : "NPC_f" );
1758  } else {
1759  // Always shouting when in danger or short time since being in danger
1763  sound, false, "speech",
1764  male ? "NPC_m_loud" : "NPC_f_loud" );
1765  }
1766 }
bool is_mute() const
Definition: character.cpp:4622
bool is_blind() const
Returns true if the player isn't able to see.
Definition: character.cpp:5996
bool is_deaf() const
Definition: character.cpp:4614
float danger_assessment() const
Definition: npc.cpp:2501
int indoor_voice() const
Definition: npc.cpp:1768
void sound(const tripoint &p, int vol, sound_t category, const std::string &description, bool ambient=false, const std::string &id="", const std::string &variant="default")
Sound at (p) of intensity (vol)
Definition: sounds.cpp:318
static const trait_id trait_MUTE("MUTE")

References _, add_msg(), add_msg_if_player_sees(), sounds::alert, danger_assessment(), Character::get_name(), get_player_character(), Character::get_shout_volume(), Character::has_trait(), indoor_voice(), Character::is_blind(), Character::is_deaf(), is_hallucination(), Character::is_mute(), line, m_warning, Character::male, NPC_DANGER_VERY_LOW, sounds::order, parse_tags(), Creature::pos(), sounds::sound(), sound, sounds::speech, string_format(), and trait_MUTE.

◆ scan_new_items()

bool npc::scan_new_items ( )

Definition at line 4142 of file npcmove.cpp.

4143 {
4144  add_msg_debug( debugmode::DF_NPC, "%s scanning new items", get_name() );
4145  if( wield_better_weapon() ) {
4146  return true;
4147  } else {
4148  // Stop "having new items" when you no longer do anything with them
4149  has_new_items = false;
4150  }
4151 
4152  return false;
4153  // TODO: Armor?
4154 }

References add_msg_debug, debugmode::DF_NPC, Character::get_name(), has_new_items, and wield_better_weapon().

Referenced by move().

◆ see_item_say_smth()

void npc::see_item_say_smth ( const itype_id object,
const std::string &  smth 
)

Definition at line 3478 of file npcmove.cpp.

3479 {
3480  map &here = get_map();
3481  for( const tripoint &p : closest_points_first( pos(), 6 ) ) {
3482  if( here.sees_some_items( p, *this ) && sees( p ) ) {
3483  for( const item &it : here.i_at( p ) ) {
3484  if( one_in( 100 ) && ( it.typeId() == object ) ) {
3485  say( smth );
3486  }
3487  }
3488  }
3489  }
3490 }

References closest_points_first(), get_map(), map::i_at(), one_in(), Creature::pos(), say(), Character::sees(), and map::sees_some_items().

Referenced by find_item().

◆ sees_dangerous_field()

bool npc::sees_dangerous_field ( const tripoint p) const
private

Definition at line 395 of file npcmove.cpp.

396 {
397  return is_dangerous_fields( get_map().field_at( p ) );
398 }
bool is_dangerous_fields(const field &fld) const
Returns true if there is a field in the field set that is dangerous to us.
Definition: creature.cpp:334

References get_map(), and Creature::is_dangerous_fields().

Referenced by could_move_onto(), get_path_avoid(), move(), and move_to().

◆ select_ammo()

item::reload_option npc::select_ammo ( const item_location base,
bool  prompt = false,
bool  empty = true 
)
overridevirtual

Select suitable ammo with which to reload the item.

Parameters
baseItem to select ammo for
promptforce display of the menu even if only one choice
emptyallow selection of empty magazines

Implements Character.

Definition at line 2175 of file npcmove.cpp.

2176 {
2177  if( !base ) {
2178  return item::reload_option();
2179  }
2180 
2181  std::vector<item::reload_option> ammo_list;
2182  list_ammo( base, ammo_list, empty );
2183 
2184  if( ammo_list.empty() ) {
2185  return item::reload_option();
2186  }
2187 
2188  // sort in order of move cost (ascending), then remaining ammo (descending) with empty magazines always last
2189  std::stable_sort( ammo_list.begin(), ammo_list.end(), []( const item::reload_option & lhs,
2190  const item::reload_option & rhs ) {
2191  if( lhs.ammo->ammo_remaining() == 0 || rhs.ammo->ammo_remaining() == 0 ) {
2192  return ( lhs.ammo->ammo_remaining() != 0 ) > ( rhs.ammo->ammo_remaining() != 0 );
2193  }
2194 
2195  if( lhs.moves() != rhs.moves() ) {
2196  return lhs.moves() < rhs.moves();
2197  }
2198 
2199  return lhs.ammo->ammo_remaining() > rhs.ammo->ammo_remaining();
2200  } );
2201 
2202  if( ammo_list[0].ammo.get_item()->ammo_remaining() > 0 ) {
2203  return ammo_list[0];
2204  } else {
2205  return item::reload_option();
2206  }
2207 }
bool list_ammo(const item_location &base, std::vector< item::reload_option > &ammo_list, bool empty=true) const
int moves() const
Definition: item.cpp:11532

References item::reload_option::ammo, item::ammo_remaining(), Character::list_ammo(), and item::reload_option::moves().

Referenced by do_reload(), find_reloadable(), and find_usable_ammo().

◆ serialize()

void npc::serialize ( JsonOut json) const
overridevirtual

Implements Character.

Definition at line 2251 of file savegame_json.cpp.

2252 {
2253  json.start_object();
2254  // This must be after the json object has been started, so any super class
2255  // puts their data into the same json object.
2256  store( json );
2257  json.end_object();
2258 }
void start_object(bool wrap=false)
Definition: json.cpp:2316
void end_object()
Definition: json.cpp:2327
void store(JsonOut &json) const

References JsonOut::end_object(), and JsonOut::start_object().

Referenced by export_to().

◆ set_attitude()

void npc::set_attitude ( npc_attitude  new_attitude)

Definition at line 3551 of file npc.cpp.

3552 {
3553  if( new_attitude == attitude ) {
3554  return;
3555  }
3557  if( new_attitude == NPCATT_FLEE ) {
3558  new_attitude = NPCATT_FLEE_TEMP;
3559  }
3560  if( new_attitude == NPCATT_FLEE_TEMP && !has_effect( effect_npc_flee_player ) ) {
3561  add_effect( effect_npc_flee_player, 24_hours );
3562  }
3563 
3564  add_msg_debug( debugmode::DF_NPC, "%s changes attitude from %s to %s",
3565  get_name(), npc_attitude_id( attitude ), npc_attitude_id( new_attitude ) );
3566  attitude_group new_group = get_attitude_group( new_attitude );
3568  if( new_group != old_group && !is_fake() && get_player_view().sees( *this ) ) {
3569  switch( new_group ) {
3571  add_msg_if_npc( m_bad, _( "<npcname> gets angry!" ) );
3572  break;
3574  add_msg_if_npc( m_warning, _( "<npcname> gets scared!" ) );
3575  break;
3576  default:
3577  if( old_group == attitude_group::hostile ) {
3578  add_msg_if_npc( m_good, _( "<npcname> calms down." ) );
3579  } else if( old_group == attitude_group::fearful ) {
3580  add_msg_if_npc( _( "<npcname> is no longer afraid." ) );
3581  }
3582  break;
3583  }
3584  }
3585  attitude = new_attitude;
3586 }
@ m_good
Definition: enums.h:347
static const efftype_id effect_npc_flee_player("npc_flee_player")
attitude_group
Definition: npc.h:134

References _, Creature::add_effect(), add_msg_debug, add_msg_if_npc(), attitude, debugmode::DF_NPC, effect_npc_flee_player, fearful, get_attitude_group(), Character::get_name(), get_player_view(), Creature::has_effect(), hostile, Creature::is_fake(), m_bad, m_good, m_warning, npc_attitude_id(), NPCATT_FLEE, NPCATT_FLEE_TEMP, previous_attitude, and Character::sees().

Referenced by address_player(), Character::assign_activity(), talk_function::assign_camp(), talk_function::assign_guard(), debug_menu::character_edit_menu(), talk_function::drop_stolen_item(), talk_effect_fun::anonymous_namespace{npctalk.cpp}::f_npc_goal(), talk_effect_fun::anonymous_namespace{npctalk.cpp}::f_wants_to_talk(), talk_function::flee(), talk_function::follow(), talk_function::follow_only(), form_opinion(), vehicle_part::get_targeting_npc(), talk_function::goto_location(), talk_function::hostile(), talk_function::insult_combat(), talk_function::lead_to_safety(), talk_function::leave(), npc_template::load(), long_term_goal_action(), make_angry(), make_fake_npc(), move(), move_to(), mug_player(), mutiny(), talk_function::npc_thankful(), pick_talk_topic(), mission_start::place_deposit_box(), talk_function::player_leaving(), regen_ai_cache(), talk_function::remove_stolen_status(), game::reset_npc_dispositions(), gun_actor::shoot(), talk_function::start_mugging(), talk_function::stop_following(), talk_function::stop_guard(), talk_function::stranger_neutral(), talker_npc::will_talk_to_u(), and witness_thievery().

◆ set_companion_mission() [1/3]

void npc::set_companion_mission ( const tripoint_abs_omt omt_pos,
const std::string &  role_id,
const mission_id miss_id 
)

Definition at line 3449 of file npc.cpp.

3451 {
3452  comp_mission.position = omt_pos;
3453  comp_mission.miss_id = miss_id;
3454  comp_mission.role_id = role_id;
3455 }

References comp_mission, npc_companion_mission::miss_id, npc_companion_mission::position, and npc_companion_mission::role_id.

◆ set_companion_mission() [2/3]

void npc::set_companion_mission ( const tripoint_abs_omt omt_pos,
const std::string &  role_id,
const mission_id miss_id,
const tripoint_abs_omt destination 
)

Definition at line 3457 of file npc.cpp.

3459 {
3460  comp_mission.position = omt_pos;
3461  comp_mission.miss_id = miss_id;
3462  comp_mission.role_id = role_id;
3463  comp_mission.destination = destination;
3464 }

References comp_mission, npc_companion_mission::destination, npc_companion_mission::miss_id, npc_companion_mission::position, and npc_companion_mission::role_id.

◆ set_companion_mission() [3/3]

void npc::set_companion_mission ( npc p,
const mission_id miss_id 
)

Set up (start) a companion mission.

Definition at line 3411 of file npc.cpp.

3412 {
3413  const tripoint_abs_omt omt_pos = p.global_omt_location();
3414  set_companion_mission( omt_pos, p.companion_mission_role_id, miss_id );
3415 }
void set_companion_mission(npc &p, const mission_id &miss_id)
Set up (start) a companion mission.
Definition: npc.cpp:3411

References companion_mission_role_id, and Creature::global_omt_location().

◆ set_fac()

void npc::set_fac ( const faction_id id)

Definition at line 747 of file npc.cpp.

748 {
749  if( my_fac ) {
750  my_fac->remove_member( getID() );
751  }
752  my_fac = g->faction_manager_ptr->get( id );
753  if( my_fac ) {
754  if( !is_fake() && !is_hallucination() ) {
756  }
757  fac_id = my_fac->id;
758  } else {
759  return;
760  }
762 }
void add_to_membership(const character_id &guy_id, const std::string &guy_name, bool known)
Definition: faction.cpp:170
void apply_ownership_to_inv()
Definition: npc.cpp:764

References faction::add_to_membership(), apply_ownership_to_inv(), Character::disp_name(), Character::fac_id, g, Character::getID(), faction_template::id, Creature::is_fake(), is_hallucination(), known_to_u, Character::my_fac, and faction::remove_member().

Referenced by avatar::control_npc(), talk_function::follow(), vehicle_part::get_targeting_npc(), talk_function::leave(), load_npc_template(), mutiny(), randomize_from_faction(), game::reset_npc_dispositions(), talker_npc::set_fac(), and update_faction_api().

◆ set_faction_ver()

void npc::set_faction_ver ( int  new_version)

Definition at line 2244 of file npc.cpp.

2245 {
2246  faction_api_version = new_version;
2247 }

References Character::faction_api_version.

Referenced by update_faction_api().

◆ set_guard_pos()

void npc::set_guard_pos ( const tripoint_abs_ms p)

Definition at line 2859 of file npcmove.cpp.

2860 {
2861  ai_cache.guard_pos = p;
2862 }

References ai_cache, and npc_short_term_cache::guard_pos.

Referenced by talk_effect_fun::anonymous_namespace{npctalk.cpp}::f_guard_pos().

◆ set_known_to_u()

void npc::set_known_to_u ( bool  known)

Definition at line 952 of file npc.cpp.

953 {
954  known_to_u = known;
955  if( my_fac ) {
957  }
958 }

References faction::add_to_membership(), Character::disp_name(), Character::getID(), known_to_u, and Character::my_fac.

Referenced by talker_npc::will_talk_to_u().

◆ set_mission()

void npc::set_mission ( npc_mission  new_mission)

◆ set_movement_mode()

void npc::set_movement_mode ( const move_mode_id mode)
overridevirtual

Implements Character.

Definition at line 5441 of file npcmove.cpp.

5442 {
5443  // Enchantments based on move modes can stack inappropriately without a recalc here
5445  move_mode = new_mode;
5446 }
void recalculate_enchantment_cache()
Definition: character.cpp:7750

References Character::recalculate_enchantment_cache().

◆ set_omt_destination()

void npc::set_omt_destination ( )

Definition at line 4851 of file npcmove.cpp.

4852 {
4853  /* TODO: Make NPCs' movement more intelligent.
4854  * Right now this function just makes them attempt to address their needs:
4855  * if we need ammo, go to a gun store, if we need food, go to a grocery store,
4856  * and if we don't have any needs, pick a random spot.
4857  * What it SHOULD do is that, if there's time; but also look at our mission and
4858  * our faction to determine more meaningful actions, such as attacking a rival
4859  * faction's base, or meeting up with someone friendly. NPCs should also
4860  * attempt to reach safety before nightfall, and possibly similar goals.
4861  * Also, NPCs should be able to assign themselves missions like "break into that
4862  * lab" or "map that river bank."
4863  */
4864  if( is_stationary( true ) ) {
4866  return;
4867  }
4868 
4869  tripoint_abs_omt surface_omt_loc = global_omt_location();
4870  // We need that, otherwise find_closest won't work properly
4871  surface_omt_loc.z() = 0;
4872 
4873  decide_needs();
4874  if( needs.empty() ) { // We don't need anything in particular.
4875  needs.push_back( need_none );
4876 
4877  // also, don't bother looking if the CITY_SIZE is 0, just go somewhere at random
4878  const int city_size = get_option<int>( "CITY_SIZE" );
4879  if( city_size == 0 ) {
4880  goal = surface_omt_loc + point( rng( -90, 90 ), rng( -90, 90 ) );
4881  return;
4882  }
4883  }
4884 
4885  std::string dest_type;
4886  for( const npc_need &fulfill : needs ) {
4887  auto cache_iter = goal_cache.find( fulfill );
4888  if( cache_iter != goal_cache.end() && cache_iter->second.omt_loc == surface_omt_loc ) {
4889  goal = cache_iter->second.goal;
4890  } else {
4891  // look for the closest occurrence of any of that locations terrain types
4892  omt_find_params find_params;
4893  for( const oter_type_str_id &elem : get_location_for( fulfill )->get_all_terrains() ) {
4894  std::pair<std::string, ot_match_type> temp_pair;
4895  temp_pair.first = elem.str();
4896  temp_pair.second = ot_match_type::type;
4897  find_params.types.push_back( temp_pair );
4898  }
4899  // note: no shuffle of `find_params.types` is needed, because `find_closest`
4900  // disregards `types` order anyway, and already returns random result among
4901  // those having equal minimal distance
4902  find_params.search_range = 75;
4903  find_params.existing_only = false;
4904  // force finding goal on the same zlevel (for random spawned NPCs that's z=0), otherwise
4905  // we may target unreachable overmap tiles (no ramp up/down) which makes
4906  // overmap_buffer.get_travel_path waste a lot of time
4907  find_params.min_z = surface_omt_loc.z();
4908  find_params.max_z = surface_omt_loc.z();
4909  goal = overmap_buffer.find_closest( surface_omt_loc, find_params );
4910  npc_need_goal_cache &cache = goal_cache[fulfill];
4911  cache.goal = goal;
4912  cache.omt_loc = surface_omt_loc;
4913  }
4914  omt_path.clear();
4915  if( goal != overmap::invalid_tripoint ) {
4917  }
4918  if( !omt_path.empty() ) {
4919  dest_type = overmap_buffer.ter( goal )->get_type_id().str();
4920  break;
4921  }
4922  }
4923 
4924  // couldn't find any places to go, so go somewhere.
4925  if( goal == overmap::invalid_tripoint || omt_path.empty() ) {
4926  goal = surface_omt_loc + point( rng( -90, 90 ), rng( -90, 90 ) );
4928  // try one more time
4929  if( omt_path.empty() ) {
4930  goal = surface_omt_loc + point( rng( -90, 90 ), rng( -90, 90 ) );
4932  }
4933  if( omt_path.empty() ) {
4934  goal = no_goal_point;
4935  }
4936  return;
4937  }
4938 
4939  DebugLog( D_INFO, DC_ALL ) << "npc::set_omt_destination - new goal for NPC [" << get_name() <<
4940  "] with [" << get_need_str_id( needs.front() ) <<
4941  "] is [" << dest_type <<
4942  "] in " << goal.to_string() << ".";
4943 }
static std::string get_need_str_id(const npc_need &need)
Definition: npc.cpp:3248
void guard_current_pos()
Definition: npcmove.cpp:5015
static overmap_location_str_id get_location_for(const npc_need &need)
Definition: npc.cpp:3253
std::map< npc_need, npc_need_goal_cache > goal_cache
Definition: npc.h:1350
static constexpr tripoint_abs_omt invalid_tripoint
Dummy value, used to indicate that a point returned by a function is invalid.
Definition: overmap.h:277
std::vector< tripoint_abs_omt > get_travel_path(const tripoint_abs_omt &src, const tripoint_abs_omt &dest, const overmap_path_params &params)
tripoint_abs_omt find_closest(const tripoint_abs_omt &origin, const omt_find_params &params)
Returns the closest point of terrain type.
const oter_id & ter(const tripoint_abs_omt &p)
Returns the overmap terrain at the given OMT coordinates.
std::ostream & DebugLog(DebugLevel lev, DebugClass cl)
Definition: debug.cpp:1438
@ D_INFO
Definition: debug.h:140
@ DC_ALL
Definition: debug.h:175
tripoint_abs_omt goal
Definition: npc.h:617
tripoint_abs_omt omt_loc
Definition: npc.h:618
std::vector< std::pair< std::string, ot_match_type > > types
const string_id< oter_type_t > & get_type_id() const
Definition: omdata.h:323
static overmap_path_params for_npc()

References D_INFO, DC_ALL, DebugLog(), decide_needs(), omt_find_params::existing_only, overmapbuffer::find_closest(), overmap_path_params::for_npc(), get_location_for(), Character::get_name(), get_need_str_id(), overmapbuffer::get_travel_path(), oter_t::get_type_id(), Creature::global_omt_location(), npc_need_goal_cache::goal, goal, goal_cache, guard_current_pos(), overmap::invalid_tripoint, is_stationary(), omt_find_params::max_z, omt_find_params::min_z, need_none, needs, no_goal_point, npc_need_goal_cache::omt_loc, Character::omt_path, overmap_buffer, point, rng(), omt_find_params::search_range, string_id< T >::str(), overmapbuffer::ter(), coords::coord_point_base< Point >::to_string(), type, omt_find_params::types, and coords::coord_point_mut< Point, Subpoint, InBounds >::z().

Referenced by talk_function::assign_camp(), talk_function::assign_guard(), go_to_omt_destination(), and long_term_goal_action().

◆ set_unique_id()

void npc::set_unique_id ( const std::string &  id)

Definition at line 3515 of file npc.cpp.

3516 {
3517  if( !unique_id.empty() ) {
3518  debugmsg( "Tried to set unique_id of npc with one already of value: ", unique_id );
3519  } else {
3520  unique_id = id;
3521  g->update_unique_npc_location( id, project_to<coords::om>( get_location().xy() ) );
3522  }
3523 }
character_id id
A unique ID number, assigned by the game class. Values should never be reused.
Definition: character.h:4006

References debugmsg, g, Creature::get_location(), Character::id, and unique_id.

Referenced by jmapgen_npc::apply().

◆ shift()

void npc::shift ( const point s)

Definition at line 2738 of file npc.cpp.

2739 {
2740  const point shift = sm_to_ms_copy( s );
2741  // TODO: convert these to absolute coords and get rid of shift()
2743  path.clear();
2744 }
void shift(const point &s)
Definition: npc.cpp:2738
point sm_to_ms_copy(const point &p)
static void maybe_shift(tripoint &pos, const point &d)
Definition: npc.cpp:2731

References maybe_shift(), path, point, sm_to_ms_copy(), and wanted_item_pos.

◆ shop_restock()

void npc::shop_restock ( )

Definition at line 1933 of file npc.cpp.

1934 {
1935  // Shops restock once every restock_interval
1936  time_duration const elapsed =
1938  if( ( restock != calendar::turn_zero ) && ( elapsed < 0_days ) ) {
1939  return;
1940  }
1941 
1942  if( is_player_ally() || !is_shopkeeper() ) {
1943  return;
1944  }
1946 
1947  std::vector<item_group_id> rigid_groups;
1948  std::vector<item_group_id> value_groups;
1949  for( const shopkeeper_item_group &ig : myclass->get_shopkeeper_items() ) {
1950  if( ig.can_restock( *this ) ) {
1951  if( ig.rigid ) {
1952  rigid_groups.emplace_back( ig.id );
1953  } else {
1954  value_groups.emplace_back( ig.id );
1955  }
1956  }
1957  }
1958 
1959  std::list<item> ret;
1960  int shop_value = 75000;
1961  if( my_fac ) {
1962  shop_value = my_fac->wealth * 0.0075;
1963  if( !my_fac->currency.is_empty() ) {
1964  item my_currency( my_fac->currency );
1965  if( !my_currency.is_null() ) {
1966  my_currency.set_owner( *this );
1967  int my_amount = rng( 5, 15 ) * shop_value / 100 / my_currency.price( true );
1968  for( int lcv = 0; lcv < my_amount; lcv++ ) {
1969  ret.push_back( my_currency );
1970  }
1971  }
1972  }
1973  }
1974 
1975  // First, populate trade goods using rigid groups.
1976  // Rigid groups are always processed a single time, regardless of the shopkeeper's inventory size or desired total value of goods.
1977  for( const item_group_id &rg : rigid_groups ) {
1979  if( !rigid_items.empty() ) {
1980  for( item &tmpit : rigid_items ) {
1981  if( !tmpit.is_null() ) {
1982  tmpit.set_owner( *this );
1983  ret.push_back( tmpit );
1984  }
1985  }
1986  }
1987  }
1988 
1989  // Then, populate with valued groups.
1990  // Value groups will run many times until the shopkeeper's total space is full or "shop_value" is completely spent.
1991  if( !value_groups.empty() ) {
1992  int count = 0;
1993  bool last_item = false;
1994  while( shop_value > 0 && !last_item ) {
1995  item tmpit = item_group::item_from( random_entry( value_groups ), calendar::turn );
1996  if( !tmpit.is_null() ) {
1997  tmpit.set_owner( *this );
1998  ret.push_back( tmpit );
1999  shop_value -= tmpit.price( true );
2000  count += 1;
2001  last_item = count > 10 && one_in( 100 );
2002  }
2003  }
2004 
2005  // This removes some items according to item spawn scaling factor
2006  const float spawn_rate = get_option<float>( "ITEM_SPAWNRATE" );
2007  if( spawn_rate < 1 ) {
2008  ret.remove_if( [spawn_rate]( auto & ) {
2009  return !( rng_float( 0, 1 ) < spawn_rate );
2010  } );
2011  }
2012  }
2013 
2014  add_fallback_zone( *this );
2015  consume_items_in_zones( *this, elapsed );
2017 }
itype_id last_item
Definition: character.h:2713
itype_id currency
Definition: faction.h:119
int price(bool practical) const
Returns the monetary value of an item.
Definition: item.cpp:7032
void set_owner(const faction_id &new_owner)
Definition: item.cpp:2178
const time_duration & get_shop_restock_interval() const
Definition: npc_class.cpp:452
bool is_shopkeeper() const
Definition: npc.cpp:2027
bool is_empty() const
Returns whether this id is empty.
Definition: string_id.h:303
std::vector< item > ItemList
Definition: item_group.h:50
ItemList items_from(const item_group_id &group_id, const time_point &birthday, spawn_flags flags=spawn_flags::none)
Create items from the given group.
Definition: item_group.cpp:979
item item_from(const item_group_id &group_id, const time_point &birthday)
Returns a random item from the item group, handles packaged food by putting it into its container and...
Definition: item_group.cpp:997
void consume_items_in_zones(npc &guy, time_duration const &elapsed)
void add_fallback_zone(npc &guy)
std::list< item > distribute_items_to_npc_zones(std::list< item > &items, npc &guy)
double rng_float(double lo, double hi)
Definition: rng.cpp:27

References add_fallback_zone(), consume_items_in_zones(), faction_template::currency, distribute_items_to_npc_zones(), npc_class::get_shop_restock_interval(), npc_class::get_shopkeeper_items(), string_id< T >::is_empty(), item::is_null(), is_player_ally(), is_shopkeeper(), item_group::item_from(), item_group::items_from(), Character::last_item, Character::my_fac, myclass, one_in(), item::price(), random_entry(), restock, cata::hash64_detail::ret, rng(), rng_float(), item::set_owner(), calendar::turn, calendar::turn_zero, and faction_template::wealth.

Referenced by on_load(), and npc_trading::trade().

◆ smash_ability()

int npc::smash_ability ( ) const
overridevirtual

Reimplemented from Character.

Definition at line 2491 of file npc.cpp.

2492 {
2494  // Not allowed to bash
2495  return 0;
2496  }
2497 
2498  return Character::smash_ability();
2499 }
virtual int smash_ability() const
Definition: character.cpp:3631

References allow_bash, npc_follower_rules::has_flag(), is_hallucination(), is_player_ally(), rules, and Character::smash_ability().

Referenced by can_move_to(), get_pathfinding_settings(), and move_to().

◆ spawn_at_omt()

void npc::spawn_at_omt ( const tripoint_abs_omt p)

Spawns the NPC on a random square within the given OMT.

Parameters
pglobal omt coordinates.

Definition at line 1003 of file npc.cpp.

1004 {
1005  const int max_coord = coords::map_squares_per( coords::omt ) - 1;
1006  const point_rel_ms local_pos( rng( 0, max_coord ), rng( 0, max_coord ) );
1007  spawn_at_precise( project_to<coords::ms>( p ) + local_pos );
1008 }
void spawn_at_precise(const tripoint_abs_ms &p)
Spawns the NPC on the specified map square.
Definition: npc.cpp:1010
constexpr int map_squares_per(scale s)
Definition: coordinates.h:44
constexpr scale omt
Definition: coordinates.h:40

References coords::map_squares_per(), coords::omt, rng(), and spawn_at_precise().

Referenced by overmapbuffer::fix_npcs(), and travel_overmap().

◆ spawn_at_precise()

void npc::spawn_at_precise ( const tripoint_abs_ms p)

Spawns the NPC on the specified map square.

Definition at line 1010 of file npc.cpp.

1011 {
1012  set_location( p );
1013 }

References Creature::set_location().

Referenced by map::rotate(), and spawn_at_omt().

◆ speed_rating()

float npc::speed_rating ( ) const
overridevirtual

Returns an approximate number of tiles this creature can travel per turn.

Reimplemented from Character.

Definition at line 3167 of file npc.cpp.

3168 {
3169  float ret = get_speed() / 100.0f;
3170  ret *= 100.0f / run_cost( 100, false );
3171 
3172  return ret;
3173 }

References Character::get_speed(), cata::hash64_detail::ret, and Character::run_cost().

Referenced by npc_attack_spell::base_time_penalty(), npc_attack_throw::evaluate_tripoint(), and find_dangerous_explosives().

◆ starting_weapon()

void npc::starting_weapon ( const npc_class_id type)

Definition at line 1066 of file npc.cpp.

1067 {
1068  if( item_group::group_is_defined( type->weapon_override ) ) {
1070  return;
1071  }
1072 
1074 
1075  if( best == skill_stabbing ) {
1077  } else if( best == skill_bashing ) {
1079  } else if( best == skill_cutting ) {
1081  } else if( best == skill_throw ) {
1082  set_wielded_item( random_item_from( type, "throw" ) );
1083  } else if( best == skill_archery ) {
1084  set_wielded_item( random_item_from( type, "archery" ) );
1085  } else if( best == skill_pistol ) {
1087  } else if( best == skill_shotgun ) {
1089  } else if( best == skill_smg ) {
1091  } else if( best == skill_rifle ) {
1093  }
1095  if( weapon ) {
1096  if( weapon->is_gun() ) {
1097  if( !weapon->magazine_default().is_null() ) {
1098  weapon->ammo_set( weapon->magazine_default()->magazine->default_ammo );
1099  } else if( !weapon->ammo_default().is_null() ) {
1101  } else {
1102  debugmsg( "tried setting ammo for %s which has no magazine or ammo", weapon->typeId().c_str() );
1103  }
1104  //You should be able to wield your starting weapon
1105  if( !meets_stat_requirements( *weapon ) ) {
1106  if( weapon->get_min_str() > get_str() ) {
1107  str_max = weapon->get_min_str();
1108  }
1109  if( weapon->type->min_dex > get_dex() ) {
1110  dex_max = weapon->type->min_dex;
1111  }
1112  if( weapon->type->min_int > get_int() ) {
1113  int_max = weapon->type->min_int;
1114  }
1115  if( weapon->type->min_per > get_per() ) {
1116  per_max = weapon->type->min_per;
1117  }
1118  }
1119  }
1120 
1121  cata::event e = cata::event::make<event_type::character_wields_item>( getID(), weapon->typeId() );
1122  get_event_bus().send_with_talker( this, &weapon, e );
1123 
1124  weapon->set_owner( get_faction()->id );
1125  }
1126 }
bool meets_stat_requirements(const item &it) const
Checks whether the character's stats meets the stats required by the item.
Definition: character.cpp:3539
int get_str() const
Getters for stats exclusive to characters.
Definition: character.cpp:4127
void send_with_talker(Creature *, Creature *, const cata::event &) const
Definition: event_bus.cpp:85
itype_id magazine_default(bool conversion=false) const
Get the default magazine type (if any) for the current effective ammo type.
Definition: item.cpp:11185
int get_min_str() const
Definition: item.cpp:14704
item & ammo_set(const itype_id &ammo, int qty=-1)
Filter setting the ammo for this instance Any existing ammo is removed.
Definition: item.cpp:719
itype_id ammo_default(bool conversion=true) const
Default ammo for the the item magazine pocket, if item has ammo_types().
Definition: item.cpp:11081
bool group_is_defined(const item_group_id &group_id)
Check whether an item group of the given id exists.
static const item_group_id Item_spawn_data_guns_shotgun_common("guns_shotgun_common")
static const skill_id skill_shotgun("shotgun")
static const item_group_id Item_spawn_data_guns_pistol_common("guns_pistol_common")
static const skill_id skill_archery("archery")
static const item_group_id Item_spawn_data_survivor_bashing("survivor_bashing")
static item random_item_from(const npc_class_id &type, const std::string &what, const item_group_id &fallback)
Definition: npc.cpp:786
static const item_group_id Item_spawn_data_guns_smg_common("guns_smg_common")
static const skill_id skill_smg("smg")
static const item_group_id Item_spawn_data_guns_rifle_common("guns_rifle_common")
static const skill_id skill_bashing("bashing")
static const skill_id skill_cutting("cutting")
static const item_group_id Item_spawn_data_survivor_stabbing("survivor_stabbing")
static const skill_id skill_rifle("rifle")
static const skill_id skill_throw("throw")
static const skill_id skill_pistol("pistol")
static const item_group_id Item_spawn_data_survivor_cutting("survivor_cutting")
int min_dex
Definition: itype.h:1366
int min_int
Definition: itype.h:1367
int min_per
Definition: itype.h:1368
cata::value_ptr< islot_magazine > magazine
Definition: itype.h:1209

References item::ammo_default(), item::ammo_set(), best_combat_skill(), string_id< T >::c_str(), debugmsg, Character::dex_max, Character::get_dex(), get_event_bus(), get_faction(), Character::get_int(), item::get_min_str(), Character::get_per(), Character::get_str(), Character::get_wielded_item(), Character::getID(), item_group::group_is_defined(), Character::int_max, item::is_gun(), string_id< T >::is_null(), item_group::item_from(), Item_spawn_data_guns_pistol_common, Item_spawn_data_guns_rifle_common, Item_spawn_data_guns_shotgun_common, Item_spawn_data_guns_smg_common, Item_spawn_data_survivor_bashing, Item_spawn_data_survivor_cutting, Item_spawn_data_survivor_stabbing, itype::magazine, item::magazine_default(), Character::meets_stat_requirements(), itype::min_dex, itype::min_int, itype::min_per, Character::per_max, random_item_from(), event_bus::send_with_talker(), item::set_owner(), Character::set_wielded_item(), skill_archery, skill_bashing, skill_cutting, skill_pistol, skill_rifle, skill_shotgun, skill_smg, skill_stabbing, skill_throw, Character::str_max, calendar::turn, type, item::type, item::typeId(), Character::weapon, and WEAPONS_ONLY.

Referenced by randomize().

◆ store()

void npc::store ( JsonOut json) const
protected

Definition at line 2260 of file savegame_json.cpp.

2261 {
2262  Character::store( json );
2263 
2264  json.member( "marked_for_death", marked_for_death );
2265  json.member( "dead", dead );
2266  json.member( "patience", patience );
2267  json.member( "myclass", myclass.str() );
2268  json.member( "idz", idz.str() );
2269  json.member( "known_to_u", known_to_u );
2270  json.member( "personality", personality );
2271 
2272  json.member( "last_player_seen_pos", last_player_seen_pos );
2273 
2274  json.member( "goalx", goal.x() );
2275  json.member( "goaly", goal.y() );
2276  json.member( "goalz", goal.z() );
2277 
2278  json.member( "guard_pos", guard_pos );
2279  json.member( "current_activity_id", current_activity_id.str() );
2280  json.member( "pulp_location", pulp_location );
2281  json.member( "assigned_camp", assigned_camp );
2282  json.member( "chair_pos", chair_pos );
2283  json.member( "wander_pos", wander_pos );
2284  json.member( "job", job );
2285  // TODO: stringid
2286  json.member( "mission", mission );
2287  json.member( "previous_mission", previous_mission );
2288  json.member( "faction_api_ver", faction_api_version );
2289  if( !fac_id.str().empty() ) { // set in constructor
2290  json.member( "my_fac", fac_id.c_str() );
2291  }
2292  json.member( "attitude", static_cast<int>( attitude ) );
2293  json.member( "previous_attitude", static_cast<int>( previous_attitude ) );
2294  json.member( "op_of_u", op_of_u );
2295  json.member( "chatbin", chatbin );
2296  json.member( "rules", rules );
2297 
2298  if( !real_weapon.is_null() ) {
2299  json.member( "real_weapon", real_weapon ); // also saves contents
2300  }
2301 
2302  json.member( "comp_mission_id", comp_mission.miss_id );
2303  json.member( "comp_mission_pt", comp_mission.position );
2304  json.member( "comp_mission_role", comp_mission.role_id );
2305  json.member( "companion_mission_role_id", companion_mission_role_id );
2306  json.member( "companion_mission_points", companion_mission_points );
2307  json.member( "companion_mission_time", companion_mission_time );
2308  json.member( "companion_mission_time_ret", companion_mission_time_ret );
2309  json.member( "companion_mission_inv" );
2311  json.member( "restock", restock );
2312 
2313  json.member( "complaints", complaints );
2314  json.member( "unique_id", unique_id );
2315 }
void store(item &container, item &put, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY, pocket_type pk_type=pocket_type::CONTAINER, bool check_best_pkt=false)
Stores an item inside another consuming moves proportional to weapon skill and volume.
void member(std::string_view name)
Definition: json.cpp:2422
void json_save_items(JsonOut &json) const

References JsonOut::member(), and Character::store().

◆ stow_item()

void npc::stow_item ( item it)

Definition at line 1294 of file npc.cpp.

1295 {
1296  bool stow_bionic_weapon = is_using_bionic_weapon()
1297  && get_wielded_item().get_item() == &it;
1298  if( stow_bionic_weapon ) {
1300  return;
1301  }
1302 
1303  bool avatar_sees = get_player_view().sees( pos() );
1304  if( wear_item( it, false ) ) {
1305  // Wearing the item was successful, remove weapon and post message.
1306  if( avatar_sees ) {
1307  add_msg_if_npc( m_info, _( "<npcname> wears the %s." ), it.tname() );
1308  }
1309  remove_item( it );
1310  mod_moves( -item_wear_cost( it ) );
1311  // Weapon cannot be worn or wearing was not successful. Store it in inventory if possible,
1312  // otherwise drop it.
1313  } else if( can_stash( it ) ) {
1314  item_location ret = i_add( remove_item( it ), true, nullptr, nullptr, true, false );
1315  if( avatar_sees ) {
1316  add_msg_if_npc( m_info, _( "<npcname> puts away the %s." ), ret->tname() );
1317  }
1318  mod_moves( -item_handling_cost( it ) );
1319  } else { // No room for weapon, so we drop it
1320  if( avatar_sees ) {
1321  add_msg_if_npc( m_info, _( "<npcname> drops the %s." ), it.tname() );
1322  }
1324  }
1325 }
std::optional< std::list< item >::iterator > wear_item(const item &to_wear, bool interactive=true, bool do_calc_encumbrance=true)
Wear item; returns nullopt on fail, or pointer to newly worn item on success.
int item_wear_cost(const item &it) const
Calculate (but do not deduct) the number of moves required to wear an item.
int item_handling_cost(const item &it, bool penalties=true, int base_cost=INVENTORY_HANDLING_PENALTY, int charges_in_it=-1, bool bulk_cost=false) const
Calculate (but do not deduct) the number of moves required when handling (e.g.
Definition: character.cpp:7285
item & add_item_or_charges(const tripoint &pos, item obj, bool overflow=true)
Definition: map.cpp:5177
item remove_item(item &it)
Removes and returns the item which must be contained by this instance.
Definition: visitable.cpp:543

References _, map::add_item_or_charges(), add_msg_if_npc(), Character::can_stash(), deactivate_or_discharge_bionic_weapon(), item_location::get_item(), get_map(), get_player_view(), Character::get_wielded_item(), Character::i_add(), Character::is_using_bionic_weapon(), Character::item_handling_cost(), Character::item_wear_cost(), m_info, Creature::mod_moves(), Creature::pos(), visitable::remove_item(), cata::hash64_detail::ret, viewer::sees(), item::tname(), and Character::wear_item().

Referenced by check_or_use_weapon_cbm(), discharge_cbm_weapon(), dispose_item(), and wield().

◆ theft_witness_compare()

bool npc::theft_witness_compare ( const npc lhs,
const npc rhs 
)
static

Definition at line 3588 of file npc.cpp.

3589 {
3590  const auto class_score = []( const npc * const guy ) {
3591  // Apparently a guard?
3592  if( guy->myclass == NC_BOUNTY_HUNTER ) {
3593  return 0;
3594  // If the guard? doesn't notice, the shopkeep will complain
3595  // Because they're probably the person who you have to talk to
3596  // and so will ensure the theft is noticed
3597  } else if( guy->mission == NPC_MISSION_SHOPKEEP ) {
3598  return 1;
3599  // Patrolling NPCs more likely to notice/be guards?
3600  } else if( guy->mission == NPC_MISSION_GUARD_PATROL ) {
3601  return 2;
3602  }
3603  return 3;
3604  };
3605  return class_score( lhs ) < class_score( rhs );
3606 }
const npc_class_id NC_BOUNTY_HUNTER("NC_BOUNTY_HUNTER")

References NC_BOUNTY_HUNTER, NPC_MISSION_GUARD_PATROL, and NPC_MISSION_SHOPKEEP.

Referenced by item::handle_pickup_ownership(), and monster::witness_thievery().

◆ time_to_read()

time_duration npc::time_to_read ( const item book,
const Character reader 
) const

Definition at line 1162 of file npc.cpp.

1163 {
1164  const auto &type = book.type->book;
1165  const skill_id &skill = type->skill;
1166  // The reader's reading speed has an effect only if they're trying to understand the book as they read it
1167  // Reading speed is assumed to be how well you learn from books (as opposed to hands-on experience)
1168  const bool try_understand = reader.fun_to_read( book ) ||
1169  reader.get_knowledge_level( skill ) < type->level;
1170  int reading_speed = try_understand ? std::max( reader.read_speed(), read_speed() ) : read_speed();
1171 
1172  time_duration retval = type->time * reading_speed / 100;
1173  retval *= std::min( fine_detail_vision_mod(), reader.fine_detail_vision_mod() );
1174 
1175  if( type->intel > reader.get_int() && !reader.has_trait( trait_PROF_DICEMASTER ) ) {
1176  retval += type->time * ( time_duration::from_seconds( type->intel - reader.get_int() ) /
1177  1_minutes );
1178  }
1179  return retval;
1180 }
float fine_detail_vision_mod(const tripoint &p=tripoint_min) const
Returns a value from 1.0 to 11.0 that acts as a multiplier for the time taken to perform tasks that r...
Definition: character.cpp:2791
int get_knowledge_level(const skill_id &ident) const
Definition: character.cpp:3441
bool fun_to_read(const item &book) const
Calculates the total fun bonus relative to this character's traits and chapter progress.
int read_speed() const
Returns the player's reading speed as a percentage.
Definition: character.cpp:3510
static constexpr time_duration from_seconds(const T t)
Definition: calendar.h:229
static const trait_id trait_PROF_DICEMASTER("PROF_DICEMASTER")
cata::value_ptr< islot_book > book
Definition: itype.h:1203

References itype::book, Character::fine_detail_vision_mod(), time_duration::from_seconds(), Character::fun_to_read(), Character::get_int(), Character::get_knowledge_level(), Character::has_trait(), max(), min(), Character::read_speed(), trait_PROF_DICEMASTER, type, and item::type.

Referenced by do_npc_read(), and read_activity_actor::finish().

◆ took_painkiller()

bool npc::took_painkiller ( ) const

Definition at line 2232 of file npc.cpp.

2233 {
2237 }
static const efftype_id effect_pkill_l("pkill_l")
static const efftype_id effect_pkill1_acetaminophen("pkill1_acetaminophen")
static const efftype_id effect_pkill2("pkill2")
static const efftype_id effect_pkill1_nsaid("pkill1_nsaid")
static const efftype_id effect_pkill1_generic("pkill1_generic")
static const efftype_id effect_pkill3("pkill3")

References effect_pkill1_acetaminophen, effect_pkill1_generic, effect_pkill1_nsaid, effect_pkill2, effect_pkill3, effect_pkill_l, and Creature::has_effect().

Referenced by address_needs().

◆ travel_overmap()

void npc::travel_overmap ( const tripoint_abs_omt pos)

Note: this places NPC on a given position in CURRENT MAP coordinates.

Do not use when placing a NPC in mapgen.

Definition at line 981 of file npc.cpp.

982 {
983  // TODO: fix point types
984  const point_abs_om pos_om_old = project_to<coords::om>( global_omt_location().xy() );
985  spawn_at_omt( pos );
986  const point_abs_om pos_om_new = project_to<coords::om>( global_omt_location().xy() );
987  if( global_omt_location() == goal ) {
989  }
990  if( !is_fake() && pos_om_old != pos_om_new ) {
991  overmap &om_old = overmap_buffer.get( pos_om_old );
992  overmap &om_new = overmap_buffer.get( pos_om_new );
993  if( const auto ptr = om_old.erase_npc( getID() ) ) {
994  om_new.insert_npc( ptr );
995  } else {
996  // Don't move the npc pointer around to avoid having two overmaps
997  // with the same npc pointer
998  debugmsg( "could not find npc %s on its old overmap", get_name() );
999  }
1000  }
1001 }
void spawn_at_omt(const tripoint_abs_omt &p)
Spawns the NPC on a random square within the given OMT.
Definition: npc.cpp:1003

References debugmsg, overmap::erase_npc(), overmapbuffer::get(), Character::get_name(), Character::getID(), Creature::global_omt_location(), goal, overmap::insert_npc(), Creature::is_fake(), overmap_buffer, Creature::pos(), reach_omt_destination(), and spawn_at_omt().

◆ turned_hostile()

bool npc::turned_hostile ( ) const

Definition at line 1616 of file npc.cpp.

1617 {
1618  return op_of_u.anger >= hostile_anger_level();
1619 }
int hostile_anger_level() const
Definition: npc.cpp:1621

References npc_opinion::anger, hostile_anger_level(), and op_of_u.

Referenced by talker_npc::turned_hostile().

◆ update_cardio_acc()

void npc::update_cardio_acc ( )
inlineoverridevirtual

Implements Character.

Definition at line 1177 of file npc.h.

1177 {};

◆ update_missions_target()

void npc::update_missions_target ( character_id  old_character,
character_id  new_character 
)

Definition at line 3795 of file npc.cpp.

3796 {
3797  for( ::mission *&temp : chatbin.missions_assigned ) {
3798  if( temp->get_assigned_player_id() == old_character ||
3799  temp->get_assigned_player_id() == character_id( - 1 ) ) {
3800  temp->set_assigned_player_id( new_character );
3801  }
3802  }
3803 }

References chatbin, dialogue_chatbin::missions_assigned, and temp.

◆ update_path() [1/2]

bool npc::update_path ( const tripoint p,
bool  no_bashing = false,
bool  force = true 
)

Tries to find path to p.

If it can, updates path to it.

Parameters
pDestination of pathing
no_bashingDon't allow pathing through tiles that require bashing.
forceIf there is no valid path, empty the current path.
Returns
If it updated the path.

Definition at line 2811 of file npcmove.cpp.

2812 {
2813  if( p == pos() ) {
2814  path.clear();
2815  return true;
2816  }
2817 
2818  while( !path.empty() && path[0] == pos() ) {
2819  path.erase( path.begin() );
2820  }
2821 
2822  if( !path.empty() ) {
2823  const tripoint &last = path[path.size() - 1];
2824  if( last == p && ( path[0].z != posz() || rl_dist( path[0], pos() ) <= 1 ) ) {
2825  // Our path already leads to that point, no need to recalculate
2826  return true;
2827  }
2828  }
2829 
2830  std::vector<tripoint> new_path = get_map().route( pos(), p, get_pathfinding_settings( no_bashing ),
2831  get_path_avoid() );
2832  if( new_path.empty() ) {
2833  if( !ai_cache.sound_alerts.empty() ) {
2834  ai_cache.sound_alerts.erase( ai_cache.sound_alerts.begin() );
2835  add_msg_debug( debugmode::DF_NPC, "failed to path to sound alert %d,%d,%d->%d,%d,%d",
2836  posx(), posy(), posz(), p.x, p.y, p.z );
2837  }
2838  add_msg_debug( debugmode::DF_NPC, "Failed to path %d,%d,%d->%d,%d,%d",
2839  posx(), posy(), posz(), p.x, p.y, p.z );
2840  }
2841 
2842  while( !new_path.empty() && new_path[0] == pos() ) {
2843  new_path.erase( new_path.begin() );
2844  }
2845 
2846  if( !new_path.empty() || force ) {
2847  path = std::move( new_path );
2848  return true;
2849  }
2850 
2851  return false;
2852 }

References add_msg_debug, ai_cache, debugmode::DF_NPC, force, get_map(), get_path_avoid(), get_pathfinding_settings(), last, path, Creature::pos(), Creature::posx(), Creature::posy(), Creature::posz(), rl_dist(), map::route(), npc_short_term_cache::sound_alerts, tripoint::x, tripoint::y, and tripoint::z.

Referenced by alt_attack(), execute_action(), find_corpse_to_pulp(), find_item(), good_escape_direction(), heal_player(), look_for_player(), move(), move_to(), mug_player(), pick_up_item(), reach_omt_destination(), update_path(), npc_attack_melee::use(), and worker_downtime().

◆ update_path() [2/2]

bool npc::update_path ( const tripoint_bub_ms p,
bool  no_bashing = false,
bool  force = true 
)

Definition at line 2854 of file npcmove.cpp.

2855 {
2856  return update_path( p.raw(), no_bashing, force );
2857 }

References force, coords::coord_point_mut< Point, Subpoint, InBounds >::raw(), and update_path().

◆ update_worst_item_value()

void npc::update_worst_item_value ( )

Definition at line 2040 of file npc.cpp.

2041 {
2042  worst_item_value = 99999;
2043  // TODO: Cache this
2044  int inv_val = inv->worst_item_value( this );
2045  if( inv_val < worst_item_value ) {
2046  worst_item_value = inv_val;
2047  }
2048 }

References Character::inv, and worst_item_value.

◆ use_bionic_by_id()

bool npc::use_bionic_by_id ( const bionic_id cbm_id,
bool  eff_only = false 
)

Definition at line 2248 of file npcmove.cpp.

2249 {
2250  for( bionic &i : *my_bionics ) {
2251  if( i.id == cbm_id ) {
2252  if( !i.powered ) {
2253  return activate_bionic( i, eff_only );
2254  } else {
2255  return true;
2256  }
2257  }
2258  }
2259  return false;
2260 }

References Character::activate_bionic(), and Character::my_bionics.

Referenced by address_needs(), and recharge_cbm().

◆ use_painkiller()

void npc::use_painkiller ( )

Definition at line 4425 of file npcmove.cpp.

4426 {
4427  // First, find the best painkiller for our pain level
4428  item *it = inv->most_appropriate_painkiller( get_pain() );
4429 
4430  if( it->is_null() ) {
4431  debugmsg( "NPC tried to use painkillers, but has none!" );
4432  move_pause();
4433  } else {
4434  add_msg_if_player_sees( *this, _( "%1$s takes some %2$s." ), disp_name(), it->tname() );
4435  item_location loc = item_location( *this, it );
4436  const time_duration &consume_time = get_consume_time( *loc );
4437  mod_moves( -to_moves<int>( consume_time ) );
4438  consume( loc );
4439  }
4440 }

References _, add_msg_if_player_sees(), Character::consume(), debugmsg, Character::disp_name(), Character::get_consume_time(), Creature::get_pain(), Character::inv, item::is_null(), Creature::mod_moves(), move_pause(), and item::tname().

Referenced by execute_action().

◆ value() [1/2]

double npc::value ( const item it) const

Definition at line 2050 of file npc.cpp.

2051 {
2052  if( it.is_dangerous() || ( it.has_flag( flag_BOMB ) && it.active ) ) {
2053  return -1000;
2054  }
2055 
2056  int market_price = it.price( true );
2057  return value( it, market_price );
2058 }
bool is_dangerous() const
Definition: item.cpp:14228
const flag_id flag_BOMB("BOMB")

References item::active, flag_BOMB, item::has_flag(), item::is_dangerous(), and item::price().

Referenced by npc_trading::adjusted_price(), find_item(), npc_trading::init_selling(), mug_player(), pick_up_item(), talker_npc::value(), wants_take_that(), wants_to_buy(), wants_to_sell(), and inventory::worst_item_value().

◆ value() [2/2]

double npc::value ( const item it,
double  market_price 
) const

Definition at line 2060 of file npc.cpp.

2061 {
2062  if( is_shopkeeper() ||
2063  // faction currency trades at market price
2064  ( my_fac != nullptr && my_fac->currency == it.typeId() ) ) {
2065  return market_price;
2066  }
2067 
2069  float ret = 1;
2070  if( it.is_maybe_melee_weapon() || it.is_gun() ) {
2071  // todo: remove when weapon_value takes an item_location
2072  double wield_val = weapon ? weapon_value( *weapon ) : weapon_value( null_item_reference() );
2073  double weapon_val = weapon_value( it ) - wield_val;
2074 
2075  if( weapon_val > 0 ) {
2076  ret += weapon_val * 0.0002;
2077  }
2078  }
2079 
2080  if( it.is_food() && will_eat( it ).success() ) {
2081  int const kcal_need = get_healthy_kcal() - get_stored_kcal() + stomach.get_calories();
2082  int const quench_need = get_thirst();
2083  if( kcal_need > compute_effective_nutrients( it ).kcal() * 2 ) {
2084  ret += std::min( 3.0, 0.00005 * kcal_need );
2085  }
2086  if( quench_need > it.get_comestible()->quench * 2 ) {
2087  ret += std::min( 3.0, 0.0055 * quench_need );
2088  }
2089  } else if( it.is_ammo() ) {
2090  // TODO: magazines - don't count ammo as usable if the weapon isn't.
2091  if( ( weapon && weapon->is_gun() && weapon->ammo_types().count( it.ammo_type() ) ) ||
2092  has_gun_for_ammo( it.ammo_type() ) ) {
2093  ret += 0.2;
2094  }
2095  } else if( it.is_book() ) {
2096  islot_book &book = *it.type->book;
2097  ret += book.fun * 0.01;
2098  int const skill = get_knowledge_level( book.skill );
2099  if( book.skill && skill < book.level && skill >= book.req ) {
2100  ret += ( book.level - skill ) * 0.1;
2101  }
2102  } else if( it.is_tool() && !has_amount( it.typeId(), 1 ) ) {
2103  // TODO: Sometimes we want more than one tool? Also we don't want EVERY tool.
2104  ret += 0.1;
2105  }
2106  return std::round( ret * market_price );
2107 }
bool has_gun_for_ammo(const ammotype &at) const
Check whether the player has a gun that uses the given type of ammo.
nutrients compute_effective_nutrients(const item &) const
bool is_maybe_melee_weapon() const
A heuristic on whether it's a good idea to use this as a melee weapon.
Definition: item.cpp:8601
bool is_book() const
Definition: item.cpp:9628
bool is_ammo() const
Definition: item.cpp:9470
std::set< ammotype > ammo_types(bool conversion=true) const
Ammo types (ammunition_type) the item magazine pocket can contain.
Definition: item.cpp:11056
bool has_amount(const itype_id &what, int qty, bool pseudo, const std::function< bool(const item &)> &filter) const
Definition: visitable.cpp:1018
int level
The skill level the book provides.
Definition: itype.h:519
skill_id skill
Which skill it upgrades, if any.
Definition: itype.h:511
int req
The skill level required to understand it.
Definition: itype.h:523
int fun
How fun reading this is, can be negative.
Definition: itype.h:527

References item::ammo_type(), item::ammo_types(), itype::book, Character::compute_effective_nutrients(), faction_template::currency, islot_book::fun, stomach_contents::get_calories(), item::get_comestible(), Character::get_healthy_kcal(), Character::get_knowledge_level(), Character::get_stored_kcal(), get_thirst(), Character::get_wielded_item(), visitable::has_amount(), Character::has_gun_for_ammo(), item::is_ammo(), item::is_book(), item::is_food(), item::is_gun(), item::is_maybe_melee_weapon(), is_shopkeeper(), item::is_tool(), islot_book::level, min(), Character::my_fac, null_item_reference(), islot_book::req, cata::hash64_detail::ret, round(), islot_book::skill, Character::stomach, item::type, item::typeId(), Character::weapon, Character::weapon_value(), and Character::will_eat().

◆ vehicle_danger()

float npc::vehicle_danger ( int  radius) const

Definition at line 1573 of file npc.cpp.

1574 {
1575  const tripoint from( posx() - radius, posy() - radius, posz() );
1576  const tripoint to( posx() + radius, posy() + radius, posz() );
1577  VehicleList vehicles = get_map().get_vehicles( from, to );
1578 
1579  int danger = 0;
1580 
1581  // TODO: check for most dangerous vehicle?
1582  for( size_t i = 0; i < vehicles.size(); ++i ) {
1583  const wrapped_vehicle &wrapped_veh = vehicles[i];
1584  if( wrapped_veh.v->is_moving() ) {
1585  // FIXME: this can't be the right way to do this
1586  units::angle facing = wrapped_veh.v->face.dir();
1587 
1588  point a( wrapped_veh.v->global_pos3().xy() );
1589  point b( static_cast<int>( a.x + units::cos( facing ) * radius ),
1590  static_cast<int>( a.y + units::sin( facing ) * radius ) );
1591 
1592  // fake size
1593  /* This will almost certainly give the wrong size/location on customized
1594  * vehicles. This should just count frames instead. Or actually find the
1595  * size. */
1596  vehicle_part last_part;
1597  // vehicle_part_range is a forward only iterator, see comment in vpart_range.h
1598  for( const vpart_reference &vpr : wrapped_veh.v->get_all_parts() ) {
1599  last_part = vpr.part();
1600  }
1601  int size = std::max( last_part.mount.x, last_part.mount.y );
1602 
1603  double normal = std::sqrt( static_cast<float>( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) *
1604  ( b.y - a.y ) ) );
1605  int closest = static_cast<int>( std::abs( ( posx() - a.x ) * ( b.y - a.y ) - ( posy() - a.y ) *
1606  ( b.x - a.x ) ) / normal );
1607 
1608  if( size > closest ) {
1609  danger = i;
1610  }
1611  }
1612  }
1613  return danger;
1614 }
VehicleList get_vehicles()
Definition: map.cpp:432
units::angle dir() const
Definition: tileray.cpp:73
tripoint global_pos3() const
Definition: vehicle.cpp:3431
vehicle_part_range get_all_parts() const
Yields a range containing all parts (including broken ones) that can be iterated over.
Definition: vehicle.cpp:8119
tileray face
Definition: vehicle.h:2312
bool is_moving() const
Definition: vehicle.cpp:3728
std::vector< wrapped_vehicle > VehicleList
Definition: map.h:94
double sqrt(std::vector< double > const &params)
const size_t size
Definition: omdata.h:66
constexpr units::temperature normal
double sin(angle a)
Definition: units.h:1102
double cos(angle a)
Definition: units.h:1107
int y
Definition: point.h:24
int x
Definition: point.h:23
constexpr point xy() const
Definition: point.h:202
point mount
mount point: x is on the forward/backward axis, y is on the left/right axis
Definition: vehicle.h:447
vehicle * v
Definition: map.h:91

References a, abs(), b, units::cos(), tileray::dir(), vehicle::face, Creature::facing, vehicle::get_all_parts(), get_map(), map::get_vehicles(), vehicle::global_pos3(), vehicle::is_moving(), max(), vehicle_part::mount, temperatures::normal, Creature::posx(), Creature::posy(), Creature::posz(), units::sin(), om_direction::size, sqrt(), wrapped_vehicle::v, point::x, tripoint::xy(), and point::y.

Referenced by move().

◆ wants_take_that()

bool npc::wants_take_that ( const item it)

Definition at line 3802 of file npcmove.cpp.

3803 {
3804  bool good = false;
3805  int min_value = minimum_item_value();
3806  const bool whitelisting = has_item_whitelist();
3807 
3809  if( ( ( !whitelisting && value( it ) > min_value ) || item_whitelisted( it ) ) ||
3810  weapon_value( it ) > weapon_value( weap ) ) {
3811  good = true;
3812  }
3813 
3814  return good;
3815 }
bool item_whitelisted(const item &it)
Definition: npctalk.cpp:7244

References Character::get_wielded_item(), good, has_item_whitelist(), item_whitelisted(), minimum_item_value(), null_item_reference(), value(), and Character::weapon_value().

Referenced by anonymous_namespace{npcmove.cpp}::good_for_pickup(), and npc_pickup_from_stack().

◆ wants_to_buy() [1/2]

ret_val< void > npc::wants_to_buy ( const item it,
int  at_price 
) const

Definition at line 1847 of file npc.cpp.

1848 {
1849  if( it.has_flag( flag_DANGEROUS ) || ( it.has_flag( flag_BOMB ) && it.active ) ) {
1850  return ret_val<void>::make_failure();
1851  }
1852 
1853  if( will_exchange_items_freely() ) {
1854  return ret_val<void>::make_success();
1855  }
1856 
1857  if( it.has_flag( flag_TRADER_AVOID ) || it.has_var( VAR_TRADE_IGNORE ) ) {
1858  return ret_val<void>::make_failure( _( "Will never buy this" ) );
1859  }
1860 
1861  if( !is_shopkeeper() && has_trait( trait_SQUEAMISH ) && it.is_filthy() ) {
1862  return ret_val<void>::make_failure( _( "Will not buy filthy items" ) );
1863  }
1864 
1865  icg_entry const *bl = myclass->get_shopkeeper_blacklist().matches( it, *this );
1866  if( bl != nullptr ) {
1868  }
1869 
1870  // TODO: Base on inventory
1871  return at_price >= 0 ? ret_val<void>::make_success() : ret_val<void>::make_failure();
1872 }
bool has_var(const std::string &name) const
Whether the variable is defined at all.
Definition: item.cpp:1928
bool is_filthy() const
Marks the item as filthy, so characters with squeamish trait can't wear it.
Definition: item.cpp:14652
const shopkeeper_blacklist & get_shopkeeper_blacklist() const
Definition: npc_class.cpp:431
bool will_exchange_items_freely() const
Definition: npc.cpp:1875
The class represents a composite return value of an arbitrary function (result).
Definition: ret_val.h:49
static ret_val make_success(T val=default_success::value)
Definition: ret_val.h:63
static ret_val make_failure(T val=default_failure::value)
Definition: ret_val.h:67
const flag_id flag_TRADER_AVOID("TRADER_AVOID")
const flag_id flag_DANGEROUS("DANGEROUS")
static const trait_id trait_SQUEAMISH("SQUEAMISH")
constexpr char const * VAR_TRADE_IGNORE
Definition: npctrade.h:14
translation message
icg_entry const * matches(item const &it, npc const &beta) const

References _, item::active, flag_BOMB, flag_DANGEROUS, flag_TRADER_AVOID, npc_class::get_shopkeeper_blacklist(), item::has_flag(), Character::has_trait(), item::has_var(), item::is_filthy(), is_shopkeeper(), ret_val< T >::make_failure(), ret_val< T >::make_success(), shopkeeper_blacklist::matches(), icg_entry::message, myclass, trait_SQUEAMISH, translation::translated(), VAR_TRADE_IGNORE, and will_exchange_items_freely().

◆ wants_to_buy() [2/2]

bool npc::wants_to_buy ( const item it) const

Definition at line 1842 of file npc.cpp.

1843 {
1844  return wants_to_buy( it, value( it ) ).success();
1845 }
bool wants_to_buy(const item &it) const
Definition: npc.cpp:1842

References value().

Referenced by anonymous_namespace{npctrade.cpp}::_trading_price(), trade_preset::get_denial(), and npc_trading::transfer_items().

◆ wants_to_recharge_cbm()

bool npc::wants_to_recharge_cbm ( )

Definition at line 2276 of file npcmove.cpp.

2277 {
2278  const units::energy curr_power = get_power_level();
2279  const float allowed_ratio = static_cast<int>( rules.cbm_recharge ) / 100.0f;
2280  const units::energy max_pow_allowed = get_max_power_level() * allowed_ratio;
2281 
2282  if( curr_power < max_pow_allowed ) {
2283  for( const bionic_id &bid : get_fueled_bionics() ) {
2284  if( !has_active_bionic( bid ) ) {
2285  return true;
2286  }
2287  }
2288  return get_fueled_bionics().empty(); //NPC might have power CBM that doesn't use the json fuel_opts entry
2289  }
2290  return false;
2291 }
cbm_recharge_rule cbm_recharge
Definition: npc.h:508

References npc_follower_rules::cbm_recharge, Character::get_fueled_bionics(), Character::get_max_power_level(), Character::get_power_level(), Character::has_active_bionic(), and rules.

Referenced by address_needs().

◆ wants_to_sell() [1/2]

bool npc::wants_to_sell ( const item_location it) const

Definition at line 1806 of file npc.cpp.

1807 {
1808  if( !it->is_owned_by( *this ) ) {
1809  return false;
1810  }
1811  return wants_to_sell( it, value( *it ) ).success();
1812 }
bool is_owned_by(const Character &c, bool available_to_take=false) const
Definition: item.cpp:2116
bool wants_to_sell(const item_location &it) const
Definition: npc.cpp:1806

References item::is_owned_by(), and value().

Referenced by anonymous_namespace{npctrade.cpp}::_trading_price(), bionic_install_surgeon_preset::get_denial(), trade_preset::get_denial(), npc_trading::init_selling(), and npc_trading::transfer_items().

◆ wants_to_sell() [2/2]

ret_val< void > npc::wants_to_sell ( const item_location it,
int  at_price 
) const

Definition at line 1814 of file npc.cpp.

1815 {
1816  if( will_exchange_items_freely() ) {
1817  return ret_val<void>::make_success();
1818  }
1819 
1820  // Keep items that we never want to trade and the ones we don't want to trade while in use.
1821  if( it->has_flag( flag_TRADER_KEEP ) ||
1822  is_worn( *it ) ||
1824  it.held_by( *this ) ) ) {
1825  return ret_val<void>::make_failure( _( "Won't sell their own equipment" ) );
1826  }
1827 
1828  for( const shopkeeper_item_group &ig : myclass->get_shopkeeper_items() ) {
1829  if( ig.can_sell( *this ) ) {
1830  continue;
1831  }
1832  item const *const check_it = it->this_or_single_content();
1833  if( item_group::group_contains_item( ig.id, check_it->typeId() ) ) {
1834  return ret_val<void>::make_failure( ig.get_refusal() );
1835  }
1836  }
1837 
1838  // TODO: Base on inventory
1839  return at_price >= 0 ? ret_val<void>::make_success() : ret_val<void>::make_failure();
1840 }
bool is_worn(const item &thing) const
Definition: character.h:1911
bool held_by(Character const &who) const
returns true if the item is in the inventory of the given character
item const * this_or_single_content() const
Definition: item.cpp:14971
bool sells_belongings
Definition: npc_class.h:106
const flag_id flag_TRADER_KEEP_EQUIPPED("TRADER_KEEP_EQUIPPED")
const flag_id flag_TRADER_KEEP("TRADER_KEEP")
bool group_contains_item(const item_group_id &group_id, const itype_id &)
Check whether a specific item group contains a specific item type.

References _, flag_TRADER_KEEP, flag_TRADER_KEEP_EQUIPPED, npc_class::get_shopkeeper_items(), item_group::group_contains_item(), item::has_flag(), item_location::held_by(), Character::is_worn(), ret_val< T >::make_failure(), ret_val< T >::make_success(), myclass, npc_class::sells_belongings, item::this_or_single_content(), item::typeId(), and will_exchange_items_freely().

◆ warn_about()

void npc::warn_about ( const std::string &  type,
const time_duration d = 10_minutes,
const std::string &  name = "",
int  range = -1,
const tripoint danger_pos = tripoint_zero 
)

Definition at line 5153 of file npcmove.cpp.

5155 {
5156  std::string snip;
5158  if( type == "monster" ) {
5161  } else if( type == "explosion" ) {
5164  } else if( type == "general_danger" ) {
5167  spriority = sounds::sound_t::speech;
5168  } else if( type == "relax" ) {
5171  spriority = sounds::sound_t::speech;
5172  } else if( type == "kill_npc" ) {
5175  } else if( type == "kill_player" ) {
5177  } else if( type == "run_away" ) {
5179  } else if( type == "cant_flee" ) {
5181  } else if( type == "fire_bad" ) {
5183  } else if( type == "speech_noise" && !has_trait( trait_IGNORE_SOUND ) ) {
5185  spriority = sounds::sound_t::speech;
5186  } else if( type == "combat_noise" && !has_trait( trait_IGNORE_SOUND ) ) {
5188  spriority = sounds::sound_t::speech;
5189  } else if( type == "movement_noise" && !has_trait( trait_IGNORE_SOUND ) ) {
5191  spriority = sounds::sound_t::speech;
5192  } else if( type == "heal_self" ) {
5194  spriority = sounds::sound_t::speech;
5195  } else {
5196  return;
5197  }
5198  const std::string warning_name = "warning_" + type + name;
5199  if( name.empty() ) {
5200  complain_about( warning_name, d, snip, is_enemy(), spriority );
5201  } else {
5202  const std::string range_str = range < 1 ? "<punc>" :
5203  string_format( _( " %s, %s" ),
5204  direction_name( direction_from( pos(), danger_pos ) ),
5205  distance_string( range ) );
5206  const std::string speech = string_format( _( "%s %s%s" ), snip, _( name ), range_str );
5207  complain_about( warning_name, d, speech, is_enemy(), spriority );
5208  }
5209 }
std::string distance_string(int range) const
Definition: npcmove.cpp:5140
sound_t
Definition: sounds.h:23
translation snip_combat_noise_warning
translation snip_movement_noise_warning

References _, sounds::alert, chat_snippets(), complain_about(), direction_from(), direction_name(), distance_string(), Character::has_trait(), is_enemy(), Character::name, Creature::pos(), dialogue_chatbin_snippets::snip_cant_flee, dialogue_chatbin_snippets::snip_combat_noise_warning, dialogue_chatbin_snippets::snip_fire_bad, dialogue_chatbin_snippets::snip_fire_in_the_hole, dialogue_chatbin_snippets::snip_fire_in_the_hole_h, dialogue_chatbin_snippets::snip_general_danger, dialogue_chatbin_snippets::snip_general_danger_h, dialogue_chatbin_snippets::snip_heal_self, dialogue_chatbin_snippets::snip_its_safe, dialogue_chatbin_snippets::snip_its_safe_h, dialogue_chatbin_snippets::snip_kill_npc, dialogue_chatbin_snippets::snip_kill_npc_h, dialogue_chatbin_snippets::snip_kill_player_h, dialogue_chatbin_snippets::snip_monster_warning, dialogue_chatbin_snippets::snip_monster_warning_h, dialogue_chatbin_snippets::snip_movement_noise_warning, dialogue_chatbin_snippets::snip_run_away, dialogue_chatbin_snippets::snip_speech_warning, sounds::speech, speech, string_format(), trait_IGNORE_SOUND, translation::translated(), and type.

Referenced by act_on_danger_assessment(), assess_danger(), escape_explosion(), handle_sound(), heal_self(), move_to(), and regen_ai_cache().

◆ wear_if_wanted()

bool npc::wear_if_wanted ( const item it,
std::string &  reason 
)

Definition at line 1233 of file npc.cpp.

1234 {
1235  // Note: this function isn't good enough to use with NPC AI alone
1236  // Restrict it to player's orders for now
1237  if( !it.is_armor() ) {
1238  reason = _( "This can't be worn." );
1239  return false;
1240  }
1241 
1242  // Splints ignore limits, but only when being equipped on a broken part
1243  // TODO: Drop splints when healed
1244  if( it.has_flag( flag_SPLINT ) ) {
1246  if( is_limb_broken( bp ) && !has_effect( effect_mending, bp.id() ) &&
1247  it.covers( bp ) ) {
1248  reason = chat_snippets().snip_wear.translated();
1249  return !!wear_item( it, false );
1250  }
1251  }
1252  }
1253 
1254  while( !worn.empty() ) {
1255  size_t size_before = worn.size();
1256  // Strip until we can put the new item on
1257  // This is one of the reasons this command is not used by the AI
1258  if( can_wear( it ).success() ) {
1259  // TODO: Hazmat/power armor makes this not work due to 1 boots/headgear limit
1260 
1261  if( !!wear_item( it, false ) ) {
1262  reason = chat_snippets().snip_wear.translated();
1263  return true;
1264  } else {
1265  reason = _( "I tried but couldn't wear it." );
1266  return false;
1267  }
1268  }
1269  // Otherwise, maybe we should take off one or more items and replace them
1270  bool took_off = false;
1271  for( const bodypart_id &bp : get_all_body_parts() ) {
1272  if( !it.covers( bp ) ) {
1273  continue;
1274  }
1275  // Find an item that covers the same body part as the new item
1276  item_location armor_covering = worn.first_item_covering_bp( *this, bp );
1277  if( armor_covering && !( is_limb_broken( bp ) && armor_covering->has_flag( flag_SPLINT ) ) ) {
1278  //create an item_location for player::takeoff to handle.
1279  took_off = takeoff( armor_covering );
1280  break;
1281  }
1282  }
1283 
1284  if( !took_off || worn.size() >= size_before ) {
1285  // Shouldn't happen, but does
1286  reason = _( "I tried but couldn't wear it." );
1287  return false;
1288  }
1289  }
1290  reason = chat_snippets().snip_wear.translated();
1291  return worn.empty() && wear_item( it, false );
1292 }
bool takeoff(item_location loc, std::list< item > *res=nullptr)
Takes off an item, returning false on fail.
ret_val< void > can_wear(const item &it, bool with_equip_change=false) const
Check character capable of wearing an item.
const string_id< T > & id() const
Definition: ammo_effect.cpp:33
bool is_armor() const
Definition: item.cpp:9623
bool covers(const bodypart_id &bp) const
Whether this item (when worn) covers the given body part.
Definition: item.cpp:974
size_t size() const
bool empty() const
item_location first_item_covering_bp(Character &guy, bodypart_id bp)
const flag_id flag_SPLINT("SPLINT")
static const efftype_id effect_mending("mending")

References _, bp, Character::can_wear(), chat_snippets(), item::covers(), effect_mending, outfit::empty(), outfit::first_item_covering_bp(), flag_SPLINT, Creature::get_all_body_parts(), Creature::has_effect(), item::has_flag(), int_id< T >::id(), item::is_armor(), Character::is_limb_broken(), only_main, outfit::size(), dialogue_chatbin_snippets::snip_wear, Character::takeoff(), translation::translated(), Character::wear_item(), and Character::worn.

Referenced by talker_npc::give_item_to(), and game::npc_menu().

◆ wield()

bool npc::wield ( item target)
overridevirtual

Removes currently wielded item (if any) and replaces it with the target item.

Parameters
targetreplacement item to wield or null item to remove existing weapon without replacing it
Returns
whether both removal and replacement were successful (they are performed atomically)

Implements Character.

Definition at line 1327 of file npc.cpp.

1328 {
1329  // sanity check: exit early if we're trying to wield the current weapon
1330  // needed for ranged_balance_test
1331  if( is_wielding( it ) ) {
1332  return true;
1333  }
1334 
1335  item to_wield;
1336  if( has_item( it ) ) {
1337  to_wield = remove_item( it );
1338  } else {
1339  to_wield = it;
1340  }
1343  cached_info.erase( "weapon_value" );
1345  if( has_wield_conflicts( to_wield ) ) {
1346  stow_item( *weapon );
1348  }
1349 
1350  if( to_wield.is_null() ) {
1351  set_wielded_item( item() );
1353  return true;
1354  }
1355 
1356  mod_moves( -to_wield.on_wield_cost( *this ) );
1357  if( weapon && to_wield.can_combine( *weapon ) ) {
1358  weapon->combine( to_wield );
1359  } else {
1360  set_wielded_item( to_wield );
1361  }
1362 
1364  cata::event e = cata::event::make<event_type::character_wields_item>( getID(), weapon->typeId() );
1365  get_event_bus().send_with_talker( this, &weapon, e );
1366 
1367  if( get_player_view().sees( pos() ) ) {
1368  add_msg_if_npc( m_info, _( "<npcname> wields a %s." ), weapon->tname() );
1369  }
1371  return true;
1372 }
bool has_wield_conflicts(const item &it) const
Returns true if the character is wielding something and it can't be combined with the item passed as ...
Definition: character.cpp:7894
void invalidate_leak_level_cache()
Sets leak_level_dirty to true.
Definition: character.cpp:6801
void invalidate_inventory_validity_cache()
Definition: character.cpp:3315
int on_wield_cost(const Character &you) const
Calculate (but do not deduct) the number of moves required to wield this weapon.
Definition: item.cpp:6540
bool combine(const item &rhs)
combines two items together if possible.
Definition: item.cpp:1397
bool can_combine(const item &rhs) const
Definition: item.cpp:1383
bool has_item(const item &it) const
Definition: visitable.cpp:75
@ character_wields_item

References _, add_msg_if_npc(), Character::cached_info, item::can_combine(), character_wields_item, item::combine(), get_event_bus(), get_player_view(), Character::get_wielded_item(), Character::getID(), visitable::has_item(), Character::has_wield_conflicts(), Character::invalidate_inventory_validity_cache(), Character::invalidate_leak_level_cache(), invalidate_range_cache(), item::is_null(), Character::is_wielding(), item, m_info, Creature::mod_moves(), item::on_wield_cost(), Creature::pos(), visitable::remove_item(), Character::sees(), event_bus::send(), event_bus::send_with_talker(), Character::set_wielded_item(), stow_item(), item::tname(), item::typeId(), and Character::weapon.

Referenced by talker_npc::give_item_to(), npc_attack_melee::use(), npc_attack_gun::use(), npc_attack_throw::use(), npc_attack_activate_item::use(), and wield_better_weapon().

◆ wield_better_weapon()

bool npc::wield_better_weapon ( )

Definition at line 4111 of file npcmove.cpp.

4112 {
4113  // These are also assigned here so npc::evaluate_best_weapon() can be called by itself
4114  bool can_use_gun = !is_player_ally() || rules.has_flag( ally_rule::use_guns );
4116 
4118  item &weap = weapon ? *weapon : null_item_reference();
4119  item *best = &weap;
4120 
4121  item *better_weapon = evaluate_best_weapon();
4122 
4123  if( best == better_weapon ) {
4124  add_msg_debug( debugmode::DF_NPC, "Wielded %s is best at %.1f, not switching",
4125  best->type->get_id().str(),
4126  evaluate_weapon( *better_weapon, can_use_gun, use_silent ) );
4127  return false;
4128  }
4129 
4130  add_msg_debug( debugmode::DF_NPC, "Wielding %s at value %.1f", better_weapon->type->get_id().str(),
4131  evaluate_weapon( *better_weapon, can_use_gun, use_silent ) );
4132 
4133  // Always returns true, but future proof
4134  bool wield_success = wield( *better_weapon );
4135  if( !wield_success ) {
4136  debugmsg( "NPC failed to wield better weapon %s", better_weapon->tname() );
4137  return false;
4138  }
4139  return true;
4140 }
bool wield(item &it) override
Removes currently wielded item (if any) and replaces it with the target item.
Definition: npc.cpp:1327
item * evaluate_best_weapon() const
Definition: npcmove.cpp:4064

References add_msg_debug, debugmsg, debugmode::DF_NPC, evaluate_best_weapon(), evaluate_weapon(), itype::get_id(), Character::get_wielded_item(), npc_follower_rules::has_flag(), is_player_ally(), null_item_reference(), rules, string_id< T >::str(), item::tname(), item::type, use_guns, use_silent, Character::weapon, and wield().

Referenced by talker_npc::clear_ai_rule(), move_pause(), scan_new_items(), talker_npc::set_ai_rule(), and talker_npc::toggle_ai_rule().

◆ will_accept_from_player()

bool npc::will_accept_from_player ( const item it) const

Is the item safe or does the NPC trust you enough? Is not recursive, only checks the item that is the parameter.

to check contents, call this on the items inside the item.

Definition at line 3263 of file npc.cpp.

3264 {
3265  if( is_hallucination() ) {
3266  return false;
3267  }
3268 
3270  it.has_flag( flag_NPC_SAFE ) ) {
3271  return true;
3272  }
3273 
3274  if( !it.type->use_methods.empty() ) {
3275  return false;
3276  }
3277 
3278  if( it.is_comestible() ) {
3279  if( it.get_comestible_fun() < 0 || it.poison > 0 ) {
3280  return false;
3281  }
3282  }
3283 
3284  return true;
3285 }
int get_comestible_fun() const
Definition: item.cpp:7798
int poison
Definition: item.h:3138
bool is_minion() const
Trusts you a lot.
Definition: npc.cpp:2307
const flag_id flag_NPC_SAFE("NPC_SAFE")
static const trait_id trait_DEBUG_MIND_CONTROL("DEBUG_MIND_CONTROL")

References flag_NPC_SAFE, item::get_comestible_fun(), get_player_character(), item::has_flag(), Character::has_trait(), item::is_comestible(), is_hallucination(), is_minion(), item::poison, trait_DEBUG_MIND_CONTROL, item::type, and itype::use_methods.

Referenced by try_consume().

◆ will_exchange_items_freely()

bool npc::will_exchange_items_freely ( ) const

◆ within_boundaries_of_camp()

bool npc::within_boundaries_of_camp ( ) const

Definition at line 2337 of file npc.cpp.

2338 {
2339  const point_abs_omt p( global_omt_location().xy() );
2340  for( int x2 = -3; x2 < 3; x2++ ) {
2341  for( int y2 = -3; y2 < 3; y2++ ) {
2342  const point_abs_omt nearby = p + point( x2, y2 );
2343  std::optional<basecamp *> bcp = overmap_buffer.find_camp( nearby );
2344  if( bcp ) {
2345  return true;
2346  }
2347  }
2348  }
2349  return false;
2350 }
std::vector< item_location > nearby(const std::function< bool(const item *, const item *)> &func, int radius=1) const
Returns nearby items which match the provided predicate.
Definition: character.cpp:2997

References overmapbuffer::find_camp(), Creature::global_omt_location(), Character::nearby(), overmap_buffer, and point.

◆ witness_thievery()

void npc::witness_thievery ( item it)
overridevirtual

Implements Creature.

Definition at line 1944 of file npcmove.cpp.

1945 {
1946  known_stolen_item = it;
1947  // Shopkeep is behind glass
1948  if( myclass == NC_EVAC_SHOPKEEP ) {
1949  return;
1950  }
1952 }
static const npc_class_id NC_EVAC_SHOPKEEP("NC_EVAC_SHOPKEEP")

References known_stolen_item, myclass, NC_EVAC_SHOPKEEP, NPCATT_RECOVER_GOODS, and set_attitude().

◆ wont_hit_friend()

bool npc::wont_hit_friend ( const tripoint tar,
const item it,
bool  throwing 
) const

Definition at line 2715 of file npcmove.cpp.

2716 {
2717  // TODO: Get actual dispersion instead of extracting it (badly) from confident range
2718  int confident = throwing ?
2719  confident_throw_range( it, nullptr ) :
2721  // if there is no confidence at using weapon, it's not used at range
2722  // zero confidence leads to divide by zero otherwise
2723  if( confident < 1 ) {
2724  return true;
2725  }
2726 
2727  if( rl_dist( pos(), tar ) == 1 ) {
2728  return true; // If we're *really* sure that our aim is dead-on
2729  }
2730 
2731  units::angle target_angle = coord_to_angle( pos(), tar );
2732 
2733  // TODO: Base on dispersion
2734  units::angle safe_angle = 30_degrees;
2735 
2736  for( const auto &fr : ai_cache.friends ) {
2737  const shared_ptr_fast<Creature> ally_p = fr.lock();
2738  if( !ally_p ) {
2739  continue;
2740  }
2741  const Creature &ally = *ally_p;
2742 
2743  // TODO: Extract common functions with turret target selection
2744  units::angle safe_angle_ally = safe_angle;
2745  int ally_dist = rl_dist( pos(), ally.pos() );
2746  if( ally_dist < 3 ) {
2747  safe_angle_ally += ( 3 - ally_dist ) * 30_degrees;
2748  }
2749 
2750  units::angle ally_angle = coord_to_angle( pos(), ally.pos() );
2751  units::angle angle_diff = units::fabs( ally_angle - target_angle );
2752  angle_diff = std::min( 360_degrees - angle_diff, angle_diff );
2753  if( angle_diff < safe_angle_ally ) {
2754  // TODO: Disable NPC whining is it's other NPC who prevents aiming
2755  return false;
2756  }
2757  }
2758 
2759  return true;
2760 }
double recoil_total() const
Current total maximum recoil penalty from all sources.
units::angle coord_to_angle(const tripoint &a, const tripoint &b)
Calculates the horizontal angle between the lines from (0,0,0) to a and the line from (0,...
Definition: line.cpp:940
quantity< V, U > fabs(quantity< V, U > q)
Definition: units.h:147

References ai_cache, ally, confident_shoot_range(), confident_throw_range(), coord_to_angle(), units::fabs(), npc_short_term_cache::friends, min(), Creature::pos(), Character::recoil_total(), and rl_dist().

Referenced by alt_attack(), npc_attack_gun::evaluate_tripoint(), npc_attack_throw::evaluate_tripoint(), npc_attack_gun::use(), and npc_attack_throw::use().

◆ worker_downtime()

void npc::worker_downtime ( )

Definition at line 3289 of file npcmove.cpp.

3290 {
3291  map &here = get_map();
3292  creature_tracker &creatures = get_creature_tracker();
3293  // are we already in a chair
3295  // just chill here
3296  move_pause();
3297  return;
3298  }
3299  // already know of a chair, go there - if there isn't already another creature there.
3300  // this is a bit of behind the scene omniscience for the npc, since ideally the npc
3301  // should walk to the chair and then change their destination due to the seat being taken.
3302  tripoint local_chair_pos = chair_pos ? here.getlocal( *chair_pos ) : tripoint_zero;
3303  if( chair_pos && !creatures.creature_at( local_chair_pos ) ) {
3304  if( here.has_flag_furn( ter_furn_flag::TFLAG_CAN_SIT, local_chair_pos ) ) {
3305  update_path( local_chair_pos );
3306  if( get_location() == *chair_pos || path.empty() ) {
3307  move_pause();
3308  path.clear();
3309  } else {
3310  move_to_next();
3311  }
3312  wander_pos = std::nullopt;
3313  return;
3314  } else {
3315  chair_pos = std::nullopt;
3316  }
3317  } else {
3318  // find a chair
3319  if( !is_mounted() ) {
3320  for( const tripoint &elem : here.points_in_radius( pos(), 30 ) ) {
3321  if( here.has_flag_furn( ter_furn_flag::TFLAG_CAN_SIT, elem ) && !creatures.creature_at( elem ) &&
3322  could_move_onto( elem ) &&
3323  here.point_within_camp( here.getabs( elem ) ) ) {
3324  // this one will do
3325  chair_pos = here.getglobal( elem );
3326  return;
3327  }
3328  }
3329  }
3330  }
3331  // we got here if there are no chairs available.
3332  // wander back to near the bulletin board of the camp.
3333  if( wander_pos ) {
3334  update_path( here.getlocal( *wander_pos ) );
3335  if( get_location() == *wander_pos || path.empty() ) {
3336  move_pause();
3337  path.clear();
3338  if( one_in( 30 ) ) {
3339  wander_pos = std::nullopt;
3340  }
3341  } else {
3342  move_to_next();
3343  }
3344  return;
3345  }
3346  if( assigned_camp ) {
3347  std::optional<basecamp *> bcp = overmap_buffer.find_camp( ( *assigned_camp ).xy() );
3348  if( !bcp ) {
3349  assigned_camp = std::nullopt;
3350  move_pause();
3351  return;
3352  }
3353  basecamp *temp_camp = *bcp;
3354  std::vector<tripoint> pts;
3355  for( const tripoint &elem : here.points_in_radius( here.getlocal( temp_camp->get_bb_pos() ),
3356  10 ) ) {
3357  if( creatures.creature_at( elem ) || !could_move_onto( elem ) ||
3358  here.has_flag( ter_furn_flag::TFLAG_DEEP_WATER, elem ) ||
3359  !here.has_floor_or_water( elem ) || g->is_dangerous_tile( elem ) ) {
3360  continue;
3361  }
3362  pts.push_back( elem );
3363  }
3364  if( !pts.empty() ) {
3365  wander_pos = here.getglobal( random_entry( pts ) );
3366  return;
3367  }
3368  }
3369  move_pause();
3370 }
tripoint get_bb_pos() const
Definition: basecamp.h:181
bool has_flag_furn(const std::string &flag, const tripoint &p) const
Definition: map.cpp:3112
bool point_within_camp(const tripoint &point_check) const
Definition: map.cpp:6760
tripoint getabs(const tripoint &p) const
Translates local (to this map) coordinates of a square to global absolute coordinates.
Definition: map.cpp:9614

References assigned_camp, chair_pos, could_move_onto(), creature_tracker::creature_at(), overmapbuffer::find_camp(), g, basecamp::get_bb_pos(), get_creature_tracker(), Creature::get_location(), get_map(), map::getabs(), map::getglobal(), map::getlocal(), map::has_flag(), map::has_flag_furn(), map::has_floor_or_water(), Character::is_mounted(), move_pause(), move_to_next(), one_in(), overmap_buffer, path, map::point_within_camp(), map::points_in_radius(), Creature::pos(), random_entry(), TFLAG_CAN_SIT, TFLAG_DEEP_WATER, tripoint_zero, update_path(), and wander_pos.

Referenced by execute_action().

◆ would_take_that()

bool npc::would_take_that ( const item it,
const tripoint p 
)

Definition at line 3817 of file npcmove.cpp.

3818 {
3819  const bool is_stealing = !it.is_owned_by( *this, true );
3820  if( !is_stealing ) {
3821  return true;
3822  }
3824  // Actual numeric relations are only relative to player faction
3825  if( it.is_owned_by( player ) ) {
3826  bool would_always_steal = false;
3827  int stealing_threshold = 10;
3828  // Trust = less likely to steal. Distrust? more likely!
3829  stealing_threshold += ( get_faction()->trusts_u / 5 );
3830  // We've already decided we want the item. So the primary motivator for stealing is aggression, not hoarding.
3831  stealing_threshold -= personality.aggression;
3832  stealing_threshold -= static_cast<int>( personality.collector / 3 );
3833  if( stealing_threshold < 0 ) {
3834  would_always_steal = true;
3835  }
3836  // Anyone willing to kill you no longer cares for your property rights
3838  would_always_steal = true;
3839  }
3840  if( would_always_steal ) {
3841  add_msg_debug( debugmode::DF_NPC_ITEMAI, "%s attempting to steal %s (owned by player).", get_name(),
3842  it.tname() );
3843  return true;
3844  }
3845 
3846  /*Handle player and follower vision*/
3847  viewer &player_view = get_player_view();
3848  if( player_view.sees( this->pos() ) || player_view.sees( p ) ) {
3849  return false;
3850  }
3851  std::vector<npc *> followers;
3852  for( const character_id &elem : g->get_follower_list() ) {
3853  shared_ptr_fast<npc> npc_to_get = overmap_buffer.find_npc( elem );
3854  if( !npc_to_get ) {
3855  continue;
3856  }
3857  npc *npc_to_add = npc_to_get.get();
3858  followers.push_back( npc_to_add );
3859  }
3860  for( npc *&elem : followers ) {
3861  if( elem->sees( this->pos() ) || elem->sees( p ) ) {
3862  return false;
3863  }
3864  }
3865  //Fallthrough, no consequences if you won't be caught!
3867  "%s attempting to steal %s (owned by player) because it isn't guarded.",
3868  get_name(), it.tname() );
3869  return true;
3870  }
3871 
3872 
3873  // Currently always willing to steal from other NPCs
3874  return true;
3875 }
shared_ptr_fast< npc > find_npc(character_id id)
Find the npc with the given ID.

References add_msg_debug, npc_personality::aggression, npc_personality::collector, debugmode::DF_NPC_ITEMAI, overmapbuffer::find_npc(), g, get_faction(), Character::get_name(), get_player_character(), get_player_view(), has_faction_relationship(), item::is_owned_by(), npc_factions::kill_on_sight, overmap_buffer, personality, player, viewer::sees(), item::tname(), and faction_template::trusts_u.

Referenced by anonymous_namespace{npcmove.cpp}::good_for_pickup().

Member Data Documentation

◆ ai_cache

npc_short_term_cache npc::ai_cache
private

◆ assigned_camp

std::optional<tripoint_abs_omt> npc::assigned_camp = std::nullopt

◆ attitude

npc_attitude npc::attitude = NPCATT_NULL
private

◆ base_location

std::optional<tripoint_abs_omt> npc::base_location

Definition at line 1374 of file npc.h.

Referenced by decide_needs(), and reach_omt_destination().

◆ cbm_weapon_index

int npc::cbm_weapon_index = -1
private

Definition at line 1462 of file npc.h.

◆ chair_pos

std::optional<tripoint_abs_ms> npc::chair_pos

Definition at line 1373 of file npc.h.

Referenced by import_and_clean(), and worker_downtime().

◆ chatbin

dialogue_chatbin npc::chatbin

◆ chosen_mount

weak_ptr_fast<monster> npc::chosen_mount

Definition at line 816 of file npc.h.

Referenced by talk_function::find_mount(), and activity_handlers::find_mount_do_turn().

◆ comp_mission

npc_companion_mission npc::comp_mission
private

◆ companion_mission_inv

inventory npc::companion_mission_inv

◆ companion_mission_points

std::vector<tripoint_abs_omt> npc::companion_mission_points

◆ companion_mission_role_id

std::string npc::companion_mission_role_id

◆ companion_mission_time

time_point npc::companion_mission_time

◆ companion_mission_time_ret

time_point npc::companion_mission_time_ret

◆ complaints

std::map<std::string, time_point> npc::complaints
private

Definition at line 1346 of file npc.h.

Referenced by complain_about(), and import_and_clean().

◆ confident_range_cache

std::optional<int> npc::confident_range_cache

Definition at line 1413 of file npc.h.

Referenced by assess_danger(), invalidate_range_cache(), and move().

◆ current_activity_id

activity_id npc::current_activity_id = activity_id::NULL_ID()

◆ dead

bool npc::dead = false
private

Definition at line 1464 of file npc.h.

Referenced by die(), is_dead(), and npc().

◆ fetching_item

bool npc::fetching_item = false

Definition at line 1386 of file npc.h.

Referenced by find_item(), move(), npc(), pick_up_item(), and reboot().

◆ goal

tripoint_abs_omt npc::goal

◆ goal_cache

std::map<npc_need, npc_need_goal_cache> npc::goal_cache
private

Definition at line 1350 of file npc.h.

Referenced by set_omt_destination().

◆ goto_to_this_pos

std::optional<tripoint_abs_ms> npc::goto_to_this_pos

Definition at line 1363 of file npc.h.

Referenced by execute_action(), and move().

◆ guard_pos

std::optional<tripoint_abs_ms> npc::guard_pos

◆ hallucination

bool npc::hallucination = false

Definition at line 1411 of file npc.h.

Referenced by is_hallucination(), npc(), and on_load().

◆ has_new_items

bool npc::has_new_items = false

◆ hit_by_player

bool npc::hit_by_player = false

Definition at line 1410 of file npc.h.

Referenced by die(), extended_description(), npc(), and on_attacked().

◆ idz

◆ job

job_data npc::job

◆ known_stolen_item

item* npc::known_stolen_item = nullptr

◆ known_to_u

bool npc::known_to_u = false
private

Definition at line 1344 of file npc.h.

Referenced by get_known_to_u(), set_fac(), and set_known_to_u().

◆ last_player_seen_pos

std::optional<tripoint_abs_ms> npc::last_player_seen_pos

Definition at line 1361 of file npc.h.

Referenced by execute_action(), import_and_clean(), npc(), reboot(), and saw_player_recently().

◆ last_seen_player_turn

int npc::last_seen_player_turn = 0

Definition at line 1364 of file npc.h.

Referenced by npc(), reboot(), and saw_player_recently().

◆ marked_for_death

bool npc::marked_for_death = false

Definition at line 1409 of file npc.h.

Referenced by overmap_ui::draw_ascii(), npc(), and prevent_death().

◆ mem_combat

npc_combat_memory_cache npc::mem_combat

◆ miss_ids

std::vector<mission_type_id> npc::miss_ids

Definition at line 1332 of file npc.h.

Referenced by npc_template::load(), and load_npc_template().

◆ mission

npc_mission npc::mission = NPC_MISSION_NULL

◆ myclass

npc_class_id npc::myclass

◆ need_data

std::array< std::pair< std::string, overmap_location_str_id >, npc_need::num_needs > npc::need_data
static
Initial value:
= {
{
}
}
static const overmap_location_str_id overmap_location_source_of_ammo("source_of_ammo")
static const overmap_location_str_id overmap_location_source_of_drink("source_of_drink")
static const overmap_location_str_id overmap_location_source_of_food("source_of_food")
static const overmap_location_str_id overmap_location_source_of_weapons("source_of_weapons")
static const overmap_location_str_id overmap_location_source_of_safety("source_of_safety")
static const overmap_location_str_id overmap_location_source_of_anything("source_of_anything")
static const overmap_location_str_id overmap_location_source_of_guns("source_of_guns")

Definition at line 1136 of file npc.h.

Referenced by get_location_for(), and get_need_str_id().

◆ needs

std::vector<npc_need> npc::needs

◆ no_goal_point

constexpr tripoint_abs_omt npc::no_goal_point { tripoint_min }
staticconstexpr

◆ op_of_u

npc_opinion npc::op_of_u

◆ path

std::vector<tripoint> npc::path

◆ patience

int npc::patience = 0

Definition at line 1407 of file npc.h.

Referenced by address_player(), npc(), talk_function::player_leaving(), and reboot().

◆ personality

npc_personality npc::personality

◆ prevent_death_reminder

bool npc::prevent_death_reminder = false
private

Definition at line 1466 of file npc.h.

Referenced by die(), and prevent_death().

◆ previous_attitude

npc_attitude npc::previous_attitude = NPCATT_NULL
private

Definition at line 1343 of file npc.h.

Referenced by get_previous_attitude(), revert_after_activity(), and set_attitude().

◆ previous_mission

npc_mission npc::previous_mission = NPC_MISSION_NULL

Definition at line 1401 of file npc.h.

Referenced by get_previous_mission(), import_and_clean(), revert_after_activity(), and set_mission().

◆ pulp_location

std::optional<tripoint_abs_ms> npc::pulp_location

◆ real_weapon

item npc::real_weapon
private

Definition at line 1460 of file npc.h.

Referenced by check_or_use_weapon_cbm(), and discharge_cbm_weapon().

◆ restock

time_point npc::restock

Definition at line 1385 of file npc.h.

Referenced by get_restock_interval(), and shop_restock().

◆ rules

npc_follower_rules npc::rules

◆ unique_id

std::string npc::unique_id
private

Definition at line 1477 of file npc.h.

Referenced by get_unique_id(), import_and_clean(), on_move(), and set_unique_id().

◆ wander_pos

std::optional<tripoint_abs_ms> npc::wander_pos

Definition at line 1381 of file npc.h.

Referenced by import_and_clean(), and worker_downtime().

◆ wanted_item

item_location npc::wanted_item = {}

Definition at line 1367 of file npc.h.

Referenced by find_item(), and pick_up_item().

◆ wanted_item_pos

tripoint npc::wanted_item_pos

Definition at line 1369 of file npc.h.

Referenced by find_item(), npc(), pick_up_item(), reboot(), and shift().

◆ worst_item_value

int npc::worst_item_value = 0

Definition at line 1388 of file npc.h.

Referenced by npc(), pick_up_item(), reboot(), and update_worst_item_value().


The documentation for this class was generated from the following files: